Map an object's keys to an array
JavaScript performance comparison
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.
| Test | Ops/sec | |
|---|---|---|
$.map(dimensions, function(){}) |
|
pending… |
Object.prototype.properties |
|
pending… |
var properties = function(obj) |
|
pending… |
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:
- Revision 1: published by molokoloco
- Revision 3: published by molokoloco
- Revision 4: published by molokoloco
- Revision 5: published by molokoloco and last updated
1 comment
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"]