Map an object's keys to an array

JavaScript performance comparison

Revision 5 of this test case created by molokoloco and last updated

Info

http://jsfiddle.net/molokoloco/HhnZL/

http://kangax.github.com/es5-compat-table/ : Object.keys()

There an other difference between this function : $.map() et Object.keys() do a test and don't give back own Object properties :

var dimensions = {width: 10, height: 15}; var arr1 = $.map(dimensions, function(value, index) { return index; }); console.log(arr1); //> ["width", "height"] Object.prototype.properties = function() { var p = []; for (var k in this) p.push(k); return p; }; arr2 = dimensions.properties(); console.log(arr2); //> ["width", "height", "properties"]

Preparation code

<script src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
<script>
Benchmark.prototype.setup = function() {
    var dimensions = {};
    for (var i = 0; i < 1000; i++) dimensions[i] = i;
   
    Object.prototype.properties = function() {
        var p = [];
        for (var k in this) p.push(k);
        return p;
    };
   
    var properties = function(obj) {
        var p = [];
        for (var k in obj) p.push(k);
        return p;
    };
};
</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(dimensions, function(){})
var arr = $.map(dimensions, function(value, index) {
    return index;
});
pending…
Object.prototype.properties
var arr = dimensions.properties();
pending…
var properties = function(obj)
var arr = properties(dimensions);
pending…
Object.keys(dimensions)
var arr = Object.keys(dimensions);
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:

1 comment

molokoloco (revision owner) commented :

There an other difference between this function : $.map() et Object.keys() do a test and don't give back own Object properties :

var dimensions = {width: 10, height: 15};

var arr1 = $.map(dimensions, function(value, index) { return index; }); console.log(arr1); //> ["width", "height"]

Object.prototype.properties = function() { var p = []; for (var k in this) p.push(k); return p; };

arr2 = dimensions.properties(); console.log(arr2); //> ["width", "height", "properties"]

Add a comment