Object.keys vs custom code (v2)

Revision 2 of this benchmark created on


Preparation HTML

<script>
  var obj = {
    a: 'b',
    c: 1,
    d: ['e', 'f', 'g'],
    h: {
      i: 'j',
      k: 2,
      m: [1, 2, 3]
    },
    moreComplex: {a: 1, b: {y: 'z', w: []}},
    aa: 2,
    bb: 3,
    cc: 4,
    dd: 5
  }
  
  getObjectKeys = function (object) {
      var key, keys = [];
  
      for (key in object) {
        if (object.hasOwnProperty(key)) keys.push(key);
      }
  
      return keys;
    };
  
  getObjectKeys2 = function (object) {
      if (Object.keys && typeof Object.keys === 'function') return Object.keys(object);
  
      var key, keys = [];
  
      for (key in object) {
        if (object.hasOwnProperty(key)) keys.push(key);
      }
  
      return keys;
    };
  
  getObjectKeys3 = function (object) {
      if (Object.keys) return Object.keys(object);
  
      var key, keys = [];
  
      for (key in object) {
        if (object.hasOwnProperty(key)) keys.push(key);
      }
  
      return keys;
    };
  
  getObjectKeys4 = (function () {
      if (Object.keys && typeof Object.keys === 'function') {
        return Object.keys;
      } else {
        return function(object) {
          var key, keys = [];
  
          for (key in object) {
            if (object.hasOwnProperty(key)) keys.push(key);
          }
  
          return keys;
        }
      }
    })();
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
native
var jj = Object.keys(obj);
ready
custom
var jj = getObjectKeys(obj);
ready
native w/fallback
var jj = getObjectKeys2(obj);
ready
native w/fallback (less checks)
var jj = getObjectKeys3(obj);
ready
pre-bake native or custom
var jj = getObjectKeys4(obj);
ready

Revisions

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