abaines
abaines

Reputation: 224

JavaScript: Object vs True (or other Primatives) Equality Comparison (Performance/Optimization)

So from a basic understanding of JavaScript === is faster than == (in most cases)(because === does not have to perform type-casting).

Recently I saw someone setup a high-scoped set of variables for the entire function/object/class:

var val = {}; // some random object that never changes?
var Obj = {};

then (optionally repeated) later:

Obj[key] = val;

then (optionally repeated, and possibly intertwined with above) later compared:

if ( Obj[key] === val ) {...}

My question is, why (if is it) is it faster/better than skipping val completely and just using:

Obj[key] = true; // or = 1, or something?

// ... more code, then later checking:

if ( Obj[key] === true ) // or === 1 or just ( Obj[key] ) because basic existence evaluates to true

I assume the performance lost from using true or 1 is worse than comparing an object with itself, but I'd like to understand why?

Thanks!

Upvotes: 1

Views: 69

Answers (1)

Esailija
Esailija

Reputation: 140210

This is not for performance, the object is better because it cannot be "faked". Consider:

var RED = 1,
    GREEN = 2,
    BLUE = 3;

Now if you check some color === RED, it will actually not check that, it just checks if color equals number 1, either deliberately or coincidentally.

Now in this:

var RED = {},
    GREEN = {},
    BLUE = {};

When you do, color === RED, you are really checking if the color is red because the object identity cannot be anything else.

Upvotes: 1

Related Questions