且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

检查字符串的最快方法是在JavaScript中包含另一个子字符串?

更新时间:2022-05-31 04:15:09

您有两种可能性:


  1. 正则表达式

(new RegExp('word')).test(str)
// or
/word/.test(str)


  • indexOf

    str.indexOf('word') !== -1
    


  • 正则表达式似乎更快(至少在Chrome 10中)。

    Regular expressions seem to be faster (at least in Chrome 10).

    性能测试 - 简短的草堆

    性能测试 - 长干草堆



    更新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)