Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/performance/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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/20.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 为什么String.prototype.indexOf()比for循环性能更好?_Javascript_Performance - Fatal编程技术网

Javascript 为什么String.prototype.indexOf()比for循环性能更好?

Javascript 为什么String.prototype.indexOf()比for循环性能更好?,javascript,performance,Javascript,Performance,我的印象是indexOf本质上是一个for幕后循环。但是,请考虑以下内容: const str='abcdefjhijklmnopqrstuvxy'。重复(10000)+'z'; 让前,让后; before=Date.now(); str.indexOf('z'); after=Date.now(); log('索引时间',在之后-之前); before=Date.now(); for(设i=0;i

我的印象是
indexOf
本质上是一个
for
幕后循环。但是,请考虑以下内容:

const str='abcdefjhijklmnopqrstuvxy'。重复(10000)+'z';
让前,让后;
before=Date.now();
str.indexOf('z');
after=Date.now();
log('索引时间',在之后-之前);
before=Date.now();
for(设i=0;ilog('循环时间',之后-之前)您可以对
for
循环进行一些进一步的优化:首先,不要在每次迭代中重新计算字符串的长度。其次,不要重新分配(
=
)-您想要比较(与
==
)。第三,在查看非常小的时间尺度时,使用
performance.now()
而不是
Date.now()

const str='abcdefjhijklmnopqrstuvxy'。重复(1000000)+'z';
让前,让后;
before=performance.now();
str.indexOf('z');
after=performance.now();
log('索引时间',在之后-之前);
const strArray=[…str];
const strLength=strArray.length;
before=performance.now();
for(设i=0;ilog('循环时间',之后-之前)我得到索引14的时间,循环274的时间(在我第一次运行时)。你的考试不好。对一个函数进行一次测试不足以得出任何有用的结论。你需要多次重复测试。我以后的运行在大多数情况下都会给我提供
0
4
。你至少应该指定你所说的js引擎。至于原因,这可能是因为大多数JS引擎都对常见函数(如
IndexOf
)进行了一些本机代码优化。任何合理的JavaScript浏览器实现都将是API规范定义部分的本机代码
indexOf
将以本机性能运行,而for循环将以JS解释器产生的任何性能运行。尝试
console.log(String.prototype.indexOf.toString())
,您可能会看到它被报告为
function indexOf(){[native code]}
。如果您对JIT的处理足够麻烦的话,它将做更多的工作来尝试并生成更快的代码-在所花费的时间(优化代码并执行)和所花费的时间之间取得平衡(现在就用显而易见的方式去做)。