fastest way to iterate an array

JavaScript performance comparison

Test case created by Kamyar Nazeri

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var arr = [];
    for (var i = 0; i < 1000; i++) arr.push(i);
    var len = arr.length;
};
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
while
while (len-- >= 0) {
  var o = arr[len];
}
pending…
for
for (var i = 0; i < len; i++) {
  var o = arr[i];
}
pending…
forEach
arr.forEach(function(t) {
  var o = t;
})
pending…
for-in
for (var i in arr) {
  var o = arr[i];
}
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:

0 comments

Add a comment