empty object comparisons

JavaScript performance comparison

Test case created by Russell Dempsey

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;
    }
   
    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…

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