我正在处理JavaScript的性能问题。所以我只想问:检查字符串是否包含另一个子字符串的最快方法是什么(我只需要布尔值)?您可以建议您的想法和示例代码片段吗?


当前回答

这对你有用吗?

string1.indexOf(string2) >= 0

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

编辑2:当字符串非常长和/或包含重复的模式时,RegExp可能比indexOf更快。请看评论和@Felix的回答。

其他回答

最快的

(ES6) includes

    var string = "hello",
    substring = "lo";
    string.includes(substring);

智慧指数

    var string = "hello",
    substring = "lo";
    string.indexOf(substring) !== -1;

http://jsben.ch/9cwLJ

我做了一个jsben。ch为你http://jsben.ch/#/aWxtF…似乎indexOf有点快。

根据这个网站,包含要快得多 https://www.measurethat.net/Benchmarks/Show/13675/0/regextest-vs-stringincludes-vs-stringmatch

在ES6中,includes()方法用于确定一个字符串是否可以在另一个字符串中找到,并根据需要返回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

这里是jsperf between

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

And

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

正如在jsperf中显示的结果,它们似乎都表现得很好。

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

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