views:

71

answers:

4

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?

+1  A: 

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.

ckramer
+1  A: 

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.

slifty
A: 

Hi,

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

Grz, Kris.

XIII
I need to learn to use that! Thanks.
Sam
+2  A: 

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 !.

patrick dw
@patrick Thanks for this snippet, it goes right into my snippets folder. btw is this "the" way of testing speed? or are there more efficient tools for that without the need to clutter your code.Thanks,
adardesign
@adardesign - Well, this is the method I use since I don't do it that often. You could create a separate js file with a couple of functions to start and stop the timer, and display the result, so the only clutter in your code would be the function calls. *XIII* made reference to profilers that you could try. I'm sure there are other speed testing utilities out there too. Try searching stackoverflow for info. If you can't find any, you could ask a question here regarding best methods of javascript runtime performance testing.
patrick dw