Sam
Sam

Reputation: 4487

jQuery / Javascript if statement speed

Given:

var
isIE = $.browser.msie && !$.support.opacity, 
isIE6 = isIE && $.browser.version < 7;

Which would be faster:

if(isIE6){ doSomething(); }
else { doSomethingElse(); }

OR

if(!isIE6){ doSomethingElse(); }
else { doSomething(); }

Are they exactly the same in terms of speed?

Upvotes: 3

Views: 429

Answers (4)

user113716
user113716

Reputation: 322492

Given this test on a 1,000,000 iteration loop, no difference.

var test = true;

var count = 1000000;
var stop, start = new Date();

while(count--) {
    if(test) ; // Change to !test
    else ;
}

stop = new Date();

alert(stop - start);

Tested in Firefox, Safari & IE8.

Other processes running on the system, performing the test several times in each browser returned the same general variation in milliseconds irrespective of !.

Upvotes: 4

Kris van der Mast
Kris van der Mast

Reputation: 16613

I would say that you simply test it out. There's a profiler in Firebug and also one in IE8.

Grz, Kris.

Upvotes: 0

slifty
slifty

Reputation: 13781

The first would be faster because it requires one less step (the ! operator does trigger an action separate from the if statement).

That said, there will be no real difference.

Upvotes: 1

ckramer
ckramer

Reputation: 9443

I guess technically the first may be faster because it is doing fewer operations (only checking the value) than the second (inverting the value then checking), but honestly, your not likely to notice a difference.

Upvotes: 1

Related Questions