empty object comparisons

JavaScript performance comparison

Revision 3 of this test case created by x

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 phpjs_empty (mixed_var) {
      // phpjs func see http://phpjs.org/functions/empty/
      // Checks if the argument variable is empty
      // undefined, null, false, number 0, empty string,
      // string "0", objects without properties and empty arrays
      // are considered empty
   
      var undef, key, i, len;
      var emptyValues = [undef, null, false, 0, "", "0"];
   
      for (i = 0, len = emptyValues.length; i < len; i++) {
        if (mixed_var === emptyValues[i]) {
          return true;
        }
      }
   
      if (typeof mixed_var === "object") {
        for (key in mixed_var) {
          // TODO: should we check for own properties only?
          //if (mixed_var.hasOwnProperty(key)) {
          return false;
          //}
        }
        return true;
      }
   
      return false;
    }
   
    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
es5keys(empty).length === 0;
es5keys(notEmpty).length === 0;
pending…
Object.getOwnPropertyNames ECMAScript5
es5getprops(empty).length === 0;
es5getprops(notEmpty).length === 0;
pending…
custom is_empty
is_empty(empty);
is_empty(notEmpty);
pending…
phpjs empty
phpjs_empty(empty);
phpjs_empty(notEmpty);
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