Map vs. Not

JavaScript performance comparison

Test case created

Info

Simple comparison of using a for loop to extract values from an object into two arrays vs using two map calls (and a forEach).

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var friends = [];
    var totalFriends = 10000;
    for (var i = 0; i < totalFriends; i++) {
      friends.push({
        name: 'friendly' + i.toString(), id: 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
Map
var names = friends.map(function(o) {
  return o.name;
}),
    ids = friends.map(function(o) {
    return o.id;
  });
pending…
Loop
var names = [],
    ids = [], friend;

for (var j = 0; j < totalFriends; j++) {
  friend = friends[j];
  names.push(friend.name);
  ids.push(friend.id);
}
pending…
Loop, size predeclared
var names = new Array(totalFriends),
    ids = new Array(totalFriends), friend;

for (var j = 0; j < totalFriends; j++) {
  friend = friends[j];
  names[j] = friend.name;
  ids[j] = friend.id;
}
pending…
forEach
var names = [],
    ids = [], friend;

friends.forEach(function(friend) {
  names.push(friend.name);
  ids.push(friend.id);
});
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