问题描述
我正在处理JavaScript上的性能问题。所以我只想问:检查字符串是否包含另一个子字符串的最快方法是什么(我只需要布尔值)?您能否建议您的想法和示例代码段?
I'm working with a performance issue on JavaScript. So I just want to ask: what is the fastest way to check whether a string contains another substring (I just need the boolean value)? Could you please suggest your idea and sample snippet code?
推荐答案
您有两种可能性:
-
:
str.indexOf('word') !== -1
更新2011:
不能肯定地说哪种方法更快。浏览器之间的差异是巨大的。虽然在Chrome 10中 indexOf
似乎更快,但在Safari 5中, indexOf
显然比任何其他方法都慢。
It cannot be said with certainty which method is faster. The differences between the browsers is enormous. While in Chrome 10 indexOf
seems to be faster, in Safari 5, indexOf
is clearly slower than any other method.
你必须看到并尝试自己。这取决于您的需求。例如,对于正则表达式,不区分大小写的搜索会更快。
You have to see and try for your self. It depends on your needs. For example a case-insensitive search is way faster with regular expressions.
更新2018年:
为了避免人们自己运行测试,以下是大多数常见浏览器的当前结果,百分比表示下一次浏览器的性能提升最快的结果(因浏览器而异):
Just to save people from running the tests themselves, here are the current results for most common browsers, the percentages indicate performance increase over the next fastest result (which varies between browsers):
Chrome: indexOf(快〜98%)< - 哇
Firefox:缓存RegExp(快〜18%)
IE11:缓存RegExp (快10%左右)
边缘: indexOf(快〜18%)
Safari:缓存RegExp(〜0.4 %更快)
Chrome: indexOf (~98% faster) <-- wow
Firefox: cached RegExp (~18% faster)
IE11: cached RegExp(~10% faster)
Edge: indexOf (~18% faster)
Safari: cached RegExp(~0.4% faster)
请注意缓存的RegExp 是: var r = new RegExp('simple'); var c = r.test(str);
而不是: /simple/.test(str)
这篇关于检查字符串的最快方法是在JavaScript中包含另一个子字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!