LoginSignup
1
0

More than 3 years have passed since last update.

JavaScriptの配列のループ処理(for/map/reduce)の計測

Last updated at Posted at 2021-03-14

JavaScriptの配列のループ処理を計測する。

今回計測したのは以下。
- for
- for of
- for in
- forEach
- reduce
- map

測定方法

ループ処理内では何も実行しない。
1度の実行だとはじめに実行されるループ処理が最も遅くなっため、計測対象のループ処理自体を数回実行し実行時間の平均を算出する。

const { performance } = require("perf_hooks");

// 1回の実行だと実行順序によって結果にブレがあったため何回か実行した結果の平均を取る
function measure(f, t) {
  const n = 100000;
  const s = performance.now();
  for (let i = 0; i < n; i++) {
    f(a);
  }
  // 少数第五位まで表示
  const d = 100000;
  console.log(t, " avg: ", Math.floor(((ms = performance.now() - s) / n) * d) / d);
}

// 配列の長さ - 測定に応じて数値を変える
const l = 10;
const a = [...Array(l)];

// 各loop処理の実行
measure(function (a) {for (let i = 0; i < a.length; i++) {}}, "for\t");
measure(function (a) {for (const i of a) {}}, "for of\t");
measure(function (a) {for (const i in a) {}}, "for in\t");
measure(function (a) {a.forEach(() => {});}, "forEach\t");
measure(function (a) {a.reduce(() => {});}, "reduce\t");
measure(function (a) {a.map(() => {});}, "map\t");
$ node loop.js
for       avg:  0.00005
for of    avg:  0.0001
for in    avg:  0.00048
forEach   avg:  0.00007
reduce    avg:  0.00006
map       avg:  0.0001

結果

数値はミリ秒。

処理\配列の長さ 10 100 1000 10000
for 0.00005 0.00009 0.00047 0.00417
for of 0.0001 0.00027 0.00146 0.01424
for in 0.00048 0.00286 0.02671 0.27616
forEach 0.00007 0.00025 0.00148 0.02653
reduce 0.00006 0.00031 0.00149 0.02717
map 0.0001 0.00057 0.00401 0.06101

パフォーマンスが良い順番は以下。

  1. for
  2. for of
  3. forEach reduce
  4. map
  5. for in
1
0
2

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
1
0