更快的循环:foreach与一些(jsperf的性能与node或chrome不同) [英] Faster loop: foreach vs some (performance of jsperf is different than node or chrome)

查看:107
本文介绍了更快的循环:foreach与一些(jsperf的性能与node或chrome不同)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将数组的值恢复为简单的truefalse值的最佳方法.

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

我很困惑,因为jsperf给我非常的结果与Google chrome控制台,nodejs或任何其他JS引擎给我的结果不同. (此处的jsperf代码段)

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)

这是代码段,您可以看到(可以在此处运行)some的速度比使用foreach循环快100倍

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);

问题是,为什么JSPERF给出的结果与chrome的控制台,nodejs或任何其他JS引擎不同?

正如我对下面问题的回答所指出的那样,该行为是有问题的,因为在使用JSPERF时我打开了chrome开发工具,并且所有消息都已记录到控制台,这意味着实际上结果改变了. 谨记将来,JSPERF在执行中保持打开控制台状态时可能无法正常工作.

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.

推荐答案

经过一番研究,我了解到我为使jsperf以一种奇怪的方式表现而做了什么. 我在运行jsperf测试时打开了chrome控制台

After researching a bitI understood what did I do to make jsperf behave in a strange manner. I had the chrome console open when running the jsperf tests

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

I have seen that when you open the chrome console jsperf still logs console.log and similar messages while the scripts are executing and that is what was causing the misleading result of the tests.

在此处关闭控制台窗口后,您可以看到提示...

Here you can see the tets after CLOSING the console window...

这篇关于更快的循环:foreach与一些(jsperf的性能与node或chrome不同)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆