1

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!

abaines
  • 224
  • 1
  • 5
  • 11
  • Don't worry about "performance" here - It Just Doesn't Matter. Use the approach that best represents the defined semantics of the task at hand. If you really do care about such sillyness, create/find a http://jsperf.com test-case. Note that setting up such a variable creates a *unique sentinel* which may help with semantic intent (especially if properties are added); it's not strictly about "performance". – user2246674 Sep 19 '13 at 01:28

1 Answers1

1

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.

Esailija
  • 138,174
  • 23
  • 272
  • 326