Check for property in advance or handle not having got it

JavaScript performance comparison

Test case created by T.J. Crowder

Info

Check for a property before retrieving it vs. retrieving it and then seeing if it's falsey

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var o = (function() {
        var counter = 100,
            o = {};
        while (counter-- > 0) {
            if (counter !== 6) {
                o[counter] = [counter]; // Note we're storing an array
            }
        }
        return o;
    })();
    var foundKey = 5;
    var unFoundKey = 6;
    var entry;
};
</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
Check first
if (foundKey in o) {
    if (o[foundKey][0] !== 5) throw "Error in test: Invalid value";
}
else {
    throw "Error in test: Key " + foundKey + " not found";
}
if (unFoundKey in o) {
    throw "Error in test: Key " + unFoundKey + " was found";
}
 
pending…
Get it and then test
entry = o[foundKey];
if (entry) {
    if (entry[0] !== 5) throw "Error in test: Invalid value";
}
else {
    throw "Error in test: Key " + foundKey + " not found";
}
entry = o[unFoundKey];
if (entry) {
    throw "Error in test: Key " + unFoundKey + " was found";
}
 
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