polyfill Object.keys

JavaScript performance comparison

Test case created by John Watson

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    if (!Object.keys) {
      // JScript in IE8 and below mistakenly skips over built-in properties.
      // https://developer.mozilla.org/en/ECMAScript_DontEnum_attribute
      var hasDontEnumBug = !({toString: true}).propertyIsEnumerable('toString');
   
      var getKeys = function(object) {
        var type = typeof object;
        if (type != 'object' && type != 'function' || object === null) {
          throw new TypeError('Object.keys called on non-object');
        }
   
        var keys = [];
        for (var key in object) {
          if (Object.prototype.hasOwnProperty.call(object, key)) {
            keys.push(key);
          }
        }
        return keys;
      }
   
      if (hasDontEnumBug) {
        var dontEnumProperties = [
          'toString',
          'toLocaleString',
          'valueOf',
          'hasOwnProperty',
          'isPrototypeOf',
          'prototypeIsEnumerable',
          'constructor'
        ];
   
        Object.keys = function(object) {
          var keys = getKeys(object);
          for (var ii = 0, il = dontEnumProperties.length; ii < il; ii++) {
            var property = dontEnumProperties[ii];
            if (object.hasOwnProperty(property)) {
              keys.push(property);
            }
          }
          return keys;
        };
      } else {
        Object.keys = getKeys;
      }
    }
};
</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
test1
Object.keys({a: 'a'});
 
pending…
test2
Object.keys([1]);
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