Array.forEach vs. for-loop --> scaling
JavaScript performance comparison
Info
Was trying to come up with some sort of syntactic sugar that comes closer to the prettiness of Array.forEach(fn) syntax but with the performance closer to native for-loop.
Clearly "forEach2" is not it, yet. It's currently terribly worse than either a for-loop or even forEach. :)
It's mainly because for-in-loop performance is terrible compared to for-loop: http://jsperf.com/for-loop-vs-for-in-loop
Preparation code
<script>
Array.prototype.forEach2 = function(fn, thisObj) {
var k = {};
for (var i = 0, len = this.length; i < len; i++) this.hasOwnProperty(i) && (k[i] = 0);
fn.call(thisObj, void 0, 0, this, k);
return this;
};
var arr = ['1', true, false, "", void 0, null, 2, 18.5936];
delete(arr[3]);
var arr2 = arr.slice();
for (var j = 0; j < 500; j++) {
arr2.push(Math.round(Math.random()));
}
var arr3 = arr2.slice();
for (var m = 0; m < 5000; m++) {
arr3.push(Math.round(Math.random()));
}
</script>
Test runner
Warning! For accurate results, please disable Firebug before running the tests. (Why?)
Java applet disabled.
| Test | Ops/sec | |
|---|---|---|
small array: native forEach |
|
pending… |
medium array: native forEach |
|
pending… |
big array: native forEach |
|
pending… |
small array: native for-loop |
|
pending… |
medium array: native for-loop |
|
pending… |
big array: native for-loop |
|
pending… |
small array: forEach2 + native for-loop |
|
pending… |
medium array: forEach2 + native for-loop |
|
pending… |
big array: forEach2 + native for-loop |
|
pending… |
Compare results of other browsers
Revisions
You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:
- Revision 1: published by Kyle Simpson
- Revision 3: published
- Revision 4: published
0 comments