LoginSignup
6
6

More than 5 years have passed since last update.

ブラウザ上とDeveloperコンソール上でのJS速度比較

Last updated at Posted at 2013-03-29

forEachとforに関して結果の違う二種類のベンチ結果を見て少し悩んだのですが、どうやらこれは、ブラウザ上のJavaScript と Developerコンソール上での JavaScriptの速度の違いなのかな?という気もしています。

・forEachよりforが早いベンチ
  http://jsperf.com/lo-dash-each-vs-native-foreach/3
・forとforEachが早いベンチ
  http://qiita.com/items/94d13de417e042b56d48
  http://qiita.com/items/c07329ec9500094e0ad7

ということで、同じベンチをブラウザ上で走らせた場合と、それをコンソール上で走らせた場合の比較をしてみました。

テストコードは下記の通り

var a = [];
var loopLen = 1000000;
//配列を作るa[0,1,2,3,...loopLen]
for (var i = 0; i <= loopLen; i++) a.push(i);
var aLen = a.length;

//コールバック
var cb = function (item, i) {
    if (item >= loopLen) console.timeEnd('bench');
};

console.log('===== Native for =====');
console.time('bench');
for (var i = 0; i < aLen; i++) {
    cb(a[i]);
};

console.log('===== Native forin =====');
console.time('bench');
for (var i in a) {
    cb(a[i]);
}

console.log('===== Native forEach =====');
console.time('bench');
a.forEach(function (item) {
    cb(item);
});

console.log('===== Native forEach 2 =====');
console.time('bench');
a.forEach(cb);

ブラウザ上で走らせた場合

テストコードとデモはここにあります。
http://socketapi.com/jsbu/forBench/test0.htm

===== Native for =====
bench: 39.000ms
===== Native forin =====
bench: 335.000ms
===== Native forEach =====
bench: 78.000ms
===== Native forEach 2 =====
bench: 76.000ms 

forの方が早いです。

コンソール上で走らせた場合

上記ページで、コンソールを開きテストコードをコピペして実行した結果です。

===== Native for =====
bench: 2559.000ms
===== Native forin =====
bench: 2051.000ms
===== Native forEach =====
bench: 693.000ms
===== Native forEach 2 =====
bench: 382.000ms

爆遅ですね。そのうえ、forとforEach の速度関係が逆転しています。

まぁ、実際に使うのがブラウザ上である以上、forEachよりforが早いという評価は正しいといえますね。。。

うーん。console重いとは思っていたけど、こんなことが起きていたとは。。。

せっかくなので、UnderscoreとLo-Dashも追加して比較したのも作ってあります。
http://socketapi.com/jsbu/forBench/test1.htm

===== Lo-Dash each =====
bench: 34.000ms
===== Underscore each =====
bench: 94.000ms
===== jQuery each ===== 
bench: 140.000ms 
===== Native for =====
bench: 33.000ms
===== Native forin =====
bench: 338.000ms
===== Native forEach =====
bench: 79.000ms
===== Native forEach 2=====
bench: 74.000ms 

Lo-Dash早いですね。

6
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6