Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/385.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
什么解决方案在JavaScript中搜索子字符串时执行得更快?_Javascript_String_Performance - Fatal编程技术网

什么解决方案在JavaScript中搜索子字符串时执行得更快?

什么解决方案在JavaScript中搜索子字符串时执行得更快?,javascript,string,performance,Javascript,String,Performance,我需要检查某个字符串是否包含另一个字符串(子字符串),所以 有人能告诉我哪一个性能更快: someString.includes(thisSubstring) or someString.indexOf(thisSubstring) !== -1 这取决于浏览器?有更快的解决方案吗?indexOf更快,但您可以自己轻松运行这些测试 将来,您可以使用以下模式来测量执行时间: var str1=“Nananana Catman!”; var str2=“猫人!”; var max=10000

我需要检查某个字符串是否包含另一个字符串(子字符串),所以 有人能告诉我哪一个性能更快:

someString.includes(thisSubstring) or 
someString.indexOf(thisSubstring) !== -1 

这取决于浏览器?有更快的解决方案吗?

indexOf
更快,但您可以自己轻松运行这些测试

将来,您可以使用以下模式来测量执行时间:

var str1=“Nananana Catman!”;
var str2=“猫人!”;
var max=10000000;
var t=新日期();
对于(变量i=0;i=0;
}
log(“indexOf”,new Date()-t);
t=新日期();
对于(变量i=0;i=0;
}
log(“indexOf”,new Date()-t);
t=新日期();
对于(变量i=0;iconsole.log(“包括”,新日期()-t)
indexOf
更快,但您可以自己轻松运行这些测试

将来,您可以使用以下模式来测量执行时间:

var str1=“Nananana Catman!”;
var str2=“猫人!”;
var max=10000000;
var t=新日期();
对于(变量i=0;i=0;
}
log(“indexOf”,new Date()-t);
t=新日期();
对于(变量i=0;i=0;
}
log(“indexOf”,new Date()-t);
t=新日期();
对于(变量i=0;iconsole.log(“包括”,新日期()-t)自己测量。转到,创建一个字符串,使用计时器创建一个循环,该计时器迭代n次并执行n次
包含检查。然后是另一个带有计时器的循环,它执行n
indexof
检查。然后回到这里,贴上小提琴和你的答案,哪一个更快。使用搜索。它是自己测量的副本。转到,创建一个字符串,创建一个循环,使用计时器重复n次并执行n
包含检查。然后是另一个带有计时器的循环,它执行n
indexof
检查。然后回到这里,贴上小提琴和你的答案,哪一个更快。使用搜索。这是@Prusse的翻版如果这是一个更复杂的问题,我可能会,但有了这么简单的东西,我想通过展示最简单的性能测试模式,让OP可以随心所欲地记录(私有单元测试、快速性能测试等)。@Prusse如果这是一个更复杂的问题,我可能会这样做,但通过展示最简单的性能测试模式,我想为OP提供工具,让她/他可以随心所欲地记录日志(私有单元测试、快速性能测试等)。