for vs forEach
JavaScript performance comparison
Info
Is it faster to use the native forEach or just loop with for?
Preparation code
<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
Benchmark.prototype.setup = function() {
var i, values = [],
sum = 0;
for (i = 0; i < 10000; i++) {
values[i] = i;
}
function add(val) {
sum += val;
}
};
Benchmark.prototype.teardown = function() {
var i=0, values = [],
sum = 0;
};
</script>
Preparation code output
Test runner
Warning! For accurate results, please disable Firebug before running the tests. (Why?)
Java applet disabled.
| Test | Ops/sec | |
|---|---|---|
forEach |
|
pending… |
for loop, simple |
|
pending… |
for loop, cached length |
|
pending… |
for loop, reverse |
|
pending… |
for loop, cached length, no callback |
|
pending… |
for loop, cached length, using function.call and supplying index and original array |
|
pending… |
$.each |
|
pending… |
for ... in |
|
pending… |
for loop, reverse2 |
|
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 2: published by Adrian Sutton
- Revision 3: published by Adrian Sutton
- Revision 5: published by Adrian Sutton
- Revision 9: published by alk
- Revision 10: published
- Revision 12: published
- Revision 15: published
- Revision 16: published by RubaXa
- Revision 17: published
- Revision 20: published by Brandon Satrom
- Revision 24: published
- Revision 26: published by cfddream
- Revision 27: published by cfddream
- Revision 31: published by spongman
- Revision 32: published by James Pamplin
- Revision 36: published
- Revision 37: published
- Revision 38: published by Sujay
- Revision 46: published by wicked
- Revision 47: published
- Revision 48: published by smith
- Revision 49: published by smith
- Revision 52: published
- Revision 53: published by Jean Vincent
- Revision 54: published
- Revision 56: published
- Revision 57: published by Gajus
- Revision 58: published
- Revision 59: published
- Revision 60: published
- Revision 61: published and last updated
- Revision 62: published
- Revision 63: published
- Revision 64: published
- Revision 65: published
- Revision 66: published by gerhard
- Revision 67: published
- Revision 68: published
- Revision 69: published
- Revision 70: published
- Revision 71: published
- Revision 75: published
0 comments