Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
#!/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;
}
},
lengthWithFn : function () {
function f (l) { len += l };
for (var len = 0, i = 0; i < list.length; i ++) {
f(list[i].length);
}
}
};
[14:29:55 9435] $ ./foreach-bench.js
benchmarking /Users/isaacs/Documents/src/js/node-playground/foreach-bench
Please be patient.
Scores: (bigger is better)
lengthCached
Raw:
> 3292.292292292292
> 8358
> 8361
Average (mean) 6670.43076409743
length
Raw:
> 5954
> 6228
> 6061
Average (mean) 6081
lengthWithFn
Raw:
> 3088.911088911089
> 3072
> 3098
Average (mean) 3086.303696303696
forEach
Raw:
> 2220.3389830508477
> 2561.4385614385615
> 2542
Average (mean) 2441.2591814964694
Winner: lengthCached
Compared with next highest (length), it's:
8.84% faster
1.1 times as fast
0 order(s) of magnitude faster
Compared with the slowest (forEach), it's:
63.4% faster
2.73 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