【发布时间】:2017-11-30 00:51:27
【问题描述】:
我正在尝试找出哪个性能更高:
let array = [1,2,3,4]
array.includes(4)
或
let str = "1234";
str.includes(4);
并试图通过执行来找出它:
console.time();
let ar = [1,2,3,4,5];
ar.includes(4);
console.timeEnd();
console.time();
let str = "12345";
str.includes("4");
console.timeEnd();
在控制台和页面内的脚本中。当直接从控制台执行时,array.includes 花费的时间最少。从页面执行时,报告的时间使得 string.includes 花费更少的时间。什么给了?!
【问题讨论】:
-
这是你在 jsperf.com 上的测试吗?甚至我现在也注意到了同样的事情! String.includes 在 chrome 的控制台上比在 jsperf 上快
-
是的,我刚刚在 jsperf.com/array-includes-vs-string-includes 的 jsperf 上创建了测试
-
使用 benchmarkJS 库重新创建了相同的内容。在这里查看jsfiddle.net/533hc71h/464
-
注意只有四个元素不是一个很好的测试基准。因为与
string.includes相比,array.includes可能具有轻微的初始恒定开销以及其他外部因素。将其增加到每 50 多个元素,您将在这两种情况下获得预期的结果。 -
Chrome 58.0.3029 / Windows 10 0.0.0 -- jsPerf --
Array.includes更快。String.includes的输出速度慢了 81%。
标签: javascript arrays string performance