Last active
February 21, 2020 08:05
-
-
Save wooandoo/527864f8d6e88191688222ea89fd1f7a to your computer and use it in GitHub Desktop.
array - for vs while vs forEach vs reduce (http://jsbench.github.io/#527864f8d6e88191688222ea89fd1f7a) #jsbench #jsperf
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8"/> | |
<title>array - for vs while vs forEach vs reduce</title> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/benchmark/1.0.0/benchmark.min.js"></script> | |
<script src="./suite.js"></script> | |
</head> | |
<body> | |
<h1>Open the console to view the results</h1> | |
<h2><code>cmd + alt + j</code> or <code>ctrl + alt + j</code></h2> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"use strict"; | |
(function (factory) { | |
if (typeof Benchmark !== "undefined") { | |
factory(Benchmark); | |
} else { | |
factory(require("benchmark")); | |
} | |
})(function (Benchmark) { | |
var suite = new Benchmark.Suite; | |
Benchmark.prototype.setup = function () { | |
const array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 19] | |
const forEach = (fn, array) => { | |
for (let index = 0; index < array.length; index++) { | |
fn(array[index]) | |
} | |
} | |
}; | |
suite.add("let count = 0", function () { | |
let count = 0 | |
for (let index = 0; index < array.length; index++) { | |
count += array[index] | |
} | |
}); | |
suite.add("let count = 0", function () { | |
let count = 0 | |
let index = 0 | |
while (index < array.length) { | |
count += array[index] | |
index++ | |
} | |
}); | |
suite.add("let count", function () { | |
let count | |
array.forEach(value => { | |
count += value | |
}) | |
}); | |
suite.add("let count = array.reduce(", function () { | |
let count = array.reduce( | |
(result, value) => result + value, | |
0 | |
) | |
}); | |
suite.add("let count = 0", function () { | |
let count = 0 | |
forEach(value => { count += value }, array) | |
}); | |
suite.on("cycle", function (evt) { | |
console.log(" - " + evt.target); | |
}); | |
suite.on("complete", function (evt) { | |
console.log(new Array(30).join("-")); | |
var results = evt.currentTarget.sort(function (a, b) { | |
return b.hz - a.hz; | |
}); | |
results.forEach(function (item) { | |
console.log((idx + 1) + ". " + item); | |
}); | |
}); | |
console.log("array - for vs while vs forEach vs reduce"); | |
console.log(new Array(30).join("-")); | |
suite.run(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment