4

Which is the best way to resume the value of an array into simple true or false values.

I am quite confused as jsperf is giving me VERY different results than what google chrome console, nodejs, or any other JS engine gives me. (jsperf snippet here)

Bad jsperf performance Image

This is the code snippet, and you can see (you can run it here) that some is like 100 times faster than using a foreach loop

var array = [];
var i = 0;
var flag = false;
while (i< 100000) {
    array.push(Math.random()*10000);
    i++;
}

console.time('forEach');
array.forEach((item) => {

    if (!flag && item > 10000/2) {
        flag = true;
        return;
    }
    return false
});
console.timeEnd('forEach');
console.log(flag);

flag = false;
console.time('some');
flag = array.some((item) => {

    if (item > 10000/2) {
        return true;
    }
    return false
});
console.timeEnd('some');
console.log(flag);

The question is, Why is JSPERF giving different results than chrome's console, nodejs, or any other JS engine?

EDIT: As stated by my answer to the question underneath, the behaviour was buggy, because I had the chrome dev tools open when using JSPERF, and all of the messages were being logged to the console, which means that actually the results changed. Keep in mind for the future, that JSPERF might not behave properly when leaving the console open on execution.

4

2 回答 2

10

来自MDN

除了抛出异常之外,没有其他方法可以停止或中断 forEach() 循环。

使用 a foreach,循环将准确执行 100000 次。使用some,一旦您的谓词返回 true,循环就会停止。

只要您的谓词有机会为真,some就会更有效率

于 2018-06-20T15:15:09.833 回答
2

在研究了一下之后,我明白了我做了什么让 jsperf 以一种奇怪的方式表现。运行 jsperf 测试时,我打开了 chrome 控制台

我已经看到,当您打开 chrome 控制台时,jsperf 仍然会在脚本执行时记录 console.log 和类似消息,这就是导致测试结果误导的原因。

在这里您可以在关闭控制台窗口后看到 tets ...

在此处输入图像描述

于 2018-06-20T15:13:51.470 回答