Skip to content

Instantly share code, notes, and snippets.

@jed
Forked from isaacs/foreach-bench.js
Created January 27, 2010 23:20
Show Gist options
  • Save jed/288266 to your computer and use it in GitHub Desktop.
Save jed/288266 to your computer and use it in GitHub Desktop.
#!/usr/bin/env node-bench
var list = [
"foo",
"bar",
"baz",
"quux",
"asdf",
"qwerty",
"bonk",
"whack",
"zoom",
"zap"
];
exports.compare = {
forEach : function () {
var len = 0;
list.forEach(function (item) {
len += item.length;
});
},
length : function () {
for (var len = 0, i = 0; i < list.length; i ++) {
len += list[i].length;
}
},
lengthCached : function () {
for (var len = 0, i = 0, l = list.length; i < l; i ++) {
len += list[i].length;
}
},
lengthCached2 : function () {
for (var len = 0, i = 0, l = list.length; i < l; ) {
len += list[ i++ ].length;
}
},
lengthWithFn : function () {
function f (l) { len += l };
for (var len = 0, i = 0; i < list.length; i ++) {
f(list[i].length);
}
}
};
jedbook:gist-288266 jed$ node-bench foreach-bench.js
benchmarking /Users/jed/Desktop/gist-288266/foreach-bench
Please be patient.
Scores: (bigger is better)
lengthCached2
Raw:
> 6358.358358358359
> 6390
Average (mean) 6374.179179179179
lengthCached
Raw:
> 6147
> 6244
Average (mean) 6195.5
length
Raw:
> 4536
> 4517
Average (mean) 4526.5
lengthWithFn
Raw:
> 2277
> 2279.72027972028
Average (mean) 2278.36013986014
forEach
Raw:
> 2042.9570429570429
> 2033
Average (mean) 2037.9785214785215
Winner: lengthCached2
Compared with next highest (lengthCached), it's:
2.8% faster
1.03 times as fast
0 order(s) of magnitude faster
Compared with the slowest (forEach), it's:
68.03% faster
3.13 times as fast
0 order(s) of magnitude faster
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment