Array map vs for loop

JavaScript performance comparison

Test case created

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var to_iterate = new Array(100);
    for (var i = 0; i < 100; i++) {
      to_iterate[i] = i;
    }
};
</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
For loop
var to_iter_length = to_iterate.length,
    squared = [];
for (var d = 0; d < to_iter_length; d++) {
  squared.push(Math.pow(to_iterate[d], 2));
}
pending…
Map with predefined function
function square_num(num) {
  return Math.pow(num, 2);
}
var squared = to_iterate.map(square_num);
pending…
Map with inline function
var squared = to_iterate.map(function square_num(num) {
  return Math.pow(num, 2);
});
pending…

You can edit these tests or add even more tests to this page by appending /edit to the URL.

Compare results of other browsers

0 comments

Add a comment