forEach() compared to for() and while()
JavaScript performance comparison
Info
Comparison of different methods of looping through nodelists
Preparation code
<div>
</div>
<script>
var nodes = document.getElementsByTagName("DIV");
var x;
</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 |
|
pending… |
while |
|
pending… |
while() backwards |
|
pending… |
for() with cached nodes.length |
|
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 Craig
- Revision 2: published
- Revision 3: published by Nick
- Revision 4: published by Nick
- Revision 5: published by DanMan
- Revision 6: published
- Revision 7: published by Hmm
- Revision 8: published by Serator
- Revision 9: published
- Revision 10: published
- Revision 11: published by elleestcrimi
2 comments
I added the test "for() with cached nodes.length" which saves even more time by caching the nodes.length value into another local variable. It prevents the browser from looking up the nodes.length on every iteration. Note that this should not be applied to iterations that change the nodes.length during the iteration (which might be a bad design).
This seems to be the fastest on Safari and Firefox.
Regards, Hendrik.
In the most of the languages ++i it's faster than i++ this is true in js?