empty object comparisons

JavaScript performance comparison

Revision 5 of this test case created

Info

Fastest way to check if objects are empty

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var hasOwnProperty = Object.prototype.hasOwnProperty;
    var es5keys = Object.keys;
    var es5getprops = Object.getOwnPropertyNames;
   
    function is_empty(obj) {
   
      // null and undefined are empty
      if (obj == null) return true;
      // Assume if it has a length property with a non-zero value
      // that that property is correct.
      if (obj.length && obj.length > 0) return false;
      if (obj.length === 0) return true;
   
      for (var key in obj) {
        if (hasOwnProperty.call(obj, key)) return false;
      }
   
      return true;
    }
   
    function isEmpty2(obj) {
      "use strict";
      var key;
      if (obj === null) {
        return false;
      }
      if (obj === undefined) {
        return false;
      }
      if (obj.length > 0) {
        return false;
      }
      for (key in obj) {
        if (Object.prototype.hasOwnProperty.call(obj, key)) {
          return false;
        }
      }
      return true;
    }
   
    function isEmpty3(obj) {
      "use strict";
      var hasOwnProperty, key;
      if (obj === null) {
        return false;
      }
      if (obj === undefined) {
        return false;
      }
      if (obj.length > 0) {
        return false;
      }
      hasOwnProperty = Object.prototype.hasOwnProperty;
      for (key in obj) {
        if (hasOwnProperty.call(obj, key)) {
          return false;
        }
      }
      return true;
    }
    var empty = {};
    var notEmpty = {
      foo: 'bar'
    };
};
</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
Object.keys ECMAScript5
if (es5keys(empty).length === 0) {
  return;
};
if (es5keys(notEmpty).length === 0) {
  return;
};
pending…
Object.getOwnPropertyNames ECMAScript5
if (es5getprops(empty).length === 0) {
  return;
};
if (es5getprops(notEmpty).length === 0) {
  return;
};
pending…
custom is_empty
if (is_empty(empty)) {
  return;
};
if (is_empty(notEmpty)) {
  return;
};
pending…
isEmpty2
if (isEmpty2(empty)) {
  return;
};
if (isEmpty2(notEmpty)) {
  return;
};
pending…
isEmpty3
if (isEmpty3(empty)) {
  return;
};
if (isEmpty3(notEmpty)) {
  return;
};
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:

0 comments

Add a comment