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

时间:2021-07-09 01:37:42

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?

我正在处理一个关于JavaScript的性能问题。所以我只想问:检查一个字符串是否包含另一个子字符串(我只需要布尔值)的最快方法是什么?你能提出你的想法和样本代码吗?

7 个解决方案

#1


243  

You have two possibilites:

你有两个可能性:

  1. Regular expression:

    正则表达式:

    (new RegExp('word')).test(str)
    // or
    /word/.test(str)
    
  2. indexOf:

    indexOf:

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

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

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

Performance test - short haystack
Performance test - long haystack

性能测试-短干堆性能测试-长干堆


Update 2011:

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.

不能肯定地说哪种方法更快。浏览器之间的差异是巨大的。虽然Chrome 10的indexOf似乎更快,但在Safari 5中,indexOf显然比其他任何方法都要慢。

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.

你必须看到并尝试自己。这取决于你的需要。例如,不区分大小写的搜索要比正则表达式快得多。


Update 2018:

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% faster) <-- wow
Firefox: cached RegExp (~18% faster)
IE11: cached RegExp(~10% faster)
Edge: indexOf (~18% faster)
Safari: cached RegExp(~0.4% faster)

Chrome: indexOf(快98%)<——哇! Firefox:缓存RegExp(快18%)IE11:缓存RegExp(快10%)Edge: indexOf(快18%)Safari:缓存RegExp(快0.4%)

Note that cached RegExp is: var r = new RegExp('simple'); var c = r.test(str); as opposed to: /simple/.test(str)

注意缓存的RegExp是:var r = new RegExp('simple');var c = r.test(str);而不是:/简单/ test(str)

#2


17  

Does this work for you?

这个对你有用吗?

string1.indexOf(string2) >= 0

Edit: This may not be faster than a RegExp if the string2 contains repeated patterns. On some browsers, indexOf may be much slower than RegExp. See comments.

编辑:如果string2包含重复的模式,这可能不会比RegExp快。在某些浏览器中,indexOf可能比RegExp慢得多。看到评论。

Edit 2: RegExp may be faster than indexOf when the strings are very long and/or contain repeated patterns. See comments and @Felix's answer.

编辑2:当字符串非常长并且/或包含重复的模式时,RegExp可能比indexOf更快。参见注释和@Felix的答案。

#3


7  

I've found that using a simple for loop, iterating over all elements in the string and comparing using charAt performs faster than indexOf or Regex. The code and proof is available at JSPerf.

我发现,使用简单的for循环、遍历字符串中的所有元素并使用charAt进行比较,比indexOf或Regex执行得更快。代码和证明可以在JSPerf上找到。

ETA: indexOf and charAt both perform similarly terrible on Chrome Mobile according to Browser Scope data listed on jsperf.com

根据jsperf.com上列出的浏览器范围数据,indexOf和charAt在Chrome手机上的表现同样糟糕

#4


4  

In ES6, the includes() method is used to determine whether one string may be found within another string, returning true or false as appropriate.

在ES6中,include()方法用于确定是否可以在另一个字符串中找到一个字符串,并根据需要返回true或false。

var str = 'To be, or not to be, that is the question.';

console.log(str.includes('To be'));       // true
console.log(str.includes('question'));    // true
console.log(str.includes('nonexistent')); // false

Here is jsperf between

这是jsperf之间

var ret = str.includes('one');

And

var ret = (str.indexOf('one') !== -1);

As the result shown in jsperf, it seems both of them perform well.

正如jsperf的结果所示,它们似乎都表现良好。

#5


3  

For finding a simple string, using the indexOf() method and using regex is pretty much the same: http://jsperf.com/substring - so choose which ever one that seems easier to write.

要找到一个简单的字符串,使用indexOf()方法和使用regex几乎是一样的:http://jsperf.com/substring——所以选择一个看起来更容易写的字符串。

#6


2  

I made a jsben.ch for you http://jsben.ch/#/aWxtF ...seems that indexOf is a bit faster.

我做了一个jsben。ch http://jsben。ch / # / aWxtF……似乎索引有点快。

#7


1  

It's easy way to use .match() method to string.

使用.match()方法创建字符串很容易。

var re = /(AND|OR|MAYBE)/;
var str = "IT'S MAYBE BETTER WAY TO USE .MATCH() METHOD TO STRING";
console.log('Do we found something?', Boolean(str.match(re)));

Wish you a nice day, sir!

祝您愉快,先生!

#1


243  

You have two possibilites:

你有两个可能性:

  1. Regular expression:

    正则表达式:

    (new RegExp('word')).test(str)
    // or
    /word/.test(str)
    
  2. indexOf:

    indexOf:

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

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

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

Performance test - short haystack
Performance test - long haystack

性能测试-短干堆性能测试-长干堆


Update 2011:

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.

不能肯定地说哪种方法更快。浏览器之间的差异是巨大的。虽然Chrome 10的indexOf似乎更快,但在Safari 5中,indexOf显然比其他任何方法都要慢。

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.

你必须看到并尝试自己。这取决于你的需要。例如,不区分大小写的搜索要比正则表达式快得多。


Update 2018:

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% faster) <-- wow
Firefox: cached RegExp (~18% faster)
IE11: cached RegExp(~10% faster)
Edge: indexOf (~18% faster)
Safari: cached RegExp(~0.4% faster)

Chrome: indexOf(快98%)<——哇! Firefox:缓存RegExp(快18%)IE11:缓存RegExp(快10%)Edge: indexOf(快18%)Safari:缓存RegExp(快0.4%)

Note that cached RegExp is: var r = new RegExp('simple'); var c = r.test(str); as opposed to: /simple/.test(str)

注意缓存的RegExp是:var r = new RegExp('simple');var c = r.test(str);而不是:/简单/ test(str)

#2


17  

Does this work for you?

这个对你有用吗?

string1.indexOf(string2) >= 0

Edit: This may not be faster than a RegExp if the string2 contains repeated patterns. On some browsers, indexOf may be much slower than RegExp. See comments.

编辑:如果string2包含重复的模式,这可能不会比RegExp快。在某些浏览器中,indexOf可能比RegExp慢得多。看到评论。

Edit 2: RegExp may be faster than indexOf when the strings are very long and/or contain repeated patterns. See comments and @Felix's answer.

编辑2:当字符串非常长并且/或包含重复的模式时,RegExp可能比indexOf更快。参见注释和@Felix的答案。

#3


7  

I've found that using a simple for loop, iterating over all elements in the string and comparing using charAt performs faster than indexOf or Regex. The code and proof is available at JSPerf.

我发现,使用简单的for循环、遍历字符串中的所有元素并使用charAt进行比较,比indexOf或Regex执行得更快。代码和证明可以在JSPerf上找到。

ETA: indexOf and charAt both perform similarly terrible on Chrome Mobile according to Browser Scope data listed on jsperf.com

根据jsperf.com上列出的浏览器范围数据,indexOf和charAt在Chrome手机上的表现同样糟糕

#4


4  

In ES6, the includes() method is used to determine whether one string may be found within another string, returning true or false as appropriate.

在ES6中,include()方法用于确定是否可以在另一个字符串中找到一个字符串,并根据需要返回true或false。

var str = 'To be, or not to be, that is the question.';

console.log(str.includes('To be'));       // true
console.log(str.includes('question'));    // true
console.log(str.includes('nonexistent')); // false

Here is jsperf between

这是jsperf之间

var ret = str.includes('one');

And

var ret = (str.indexOf('one') !== -1);

As the result shown in jsperf, it seems both of them perform well.

正如jsperf的结果所示,它们似乎都表现良好。

#5


3  

For finding a simple string, using the indexOf() method and using regex is pretty much the same: http://jsperf.com/substring - so choose which ever one that seems easier to write.

要找到一个简单的字符串,使用indexOf()方法和使用regex几乎是一样的:http://jsperf.com/substring——所以选择一个看起来更容易写的字符串。

#6


2  

I made a jsben.ch for you http://jsben.ch/#/aWxtF ...seems that indexOf is a bit faster.

我做了一个jsben。ch http://jsben。ch / # / aWxtF……似乎索引有点快。

#7


1  

It's easy way to use .match() method to string.

使用.match()方法创建字符串很容易。

var re = /(AND|OR|MAYBE)/;
var str = "IT'S MAYBE BETTER WAY TO USE .MATCH() METHOD TO STRING";
console.log('Do we found something?', Boolean(str.match(re)));

Wish you a nice day, sir!

祝您愉快,先生!