Skip to content

Instantly share code, notes, and snippets.

@TimothyGu
Created January 15, 2017 18:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 9 You must be signed in to fork a gist
  • Save TimothyGu/cec5fd6009b622c72311e8f447e101be to your computer and use it in GitHub Desktop.
Save TimothyGu/cec5fd6009b622c72311e8f447e101be to your computer and use it in GitHub Desktop.
for-of loop vs forEach (https://jsbench.github.io/#cec5fd6009b622c72311e8f447e101be) #jsbench #jsperf
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>for-of loop vs forEach</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>
"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 () {
var i,
value,
length,
values = [],
sum = 0,
context = values;
for (i = 0; i < 10000; i++) {
values[i] = Math.random();
}
function add(val) {
sum += val;
}
};
suite.add("values.forEach(add);", function () {
values.forEach(add);
});
suite.add("for (i = 0; i < values.length; i++) {", function () {
for (i = 0; i < values.length; i++) {
sum += values[i];
}
});
suite.add("for (value of values) {", function () {
for (value of values) {
sum += value;
}
});
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("for-of loop vs forEach");
console.log(new Array(30).join("-"));
suite.run();
});
@TwitchBronBron
Copy link

Line 58 is missing the idx variable. Should be:

results.forEach(function (item, idx) {
    console.log((idx + 1) + ". " + item);
});

Thanks for saving me half an hour by not needing to write this myself! :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment