Page 1 of 1
Fastest way to cycle through JavaScript comparisons?
Posted: Thu Nov 19, 2009 9:17 am
by Wolf_22
It's been said that a SWITCH statement can process faster than an IF in PHP. Is this true, too, for JavaScript?
I'm currently working on a JavaScript application that has approximately 9 conditions to check for in an IF block. Would it be better to use a SWITCH for this?
Re: Fastest way to cycle through JavaScript comparisons?
Posted: Thu Nov 19, 2009 9:42 am
by iankent
For the sake of 9 comparisons I wouldn't think its going to make a lot of difference. Personally I always use if/elseif for 2 or 3 comparisons and switch for any more than that. Not for any reason other than personal choice, I find switch much clearer and easier to read than lots of if's
just found this page:
http://home.earthlink.net/~kendrasg/inf ... tMain.html
there's a test that'll tell you how long switch/if-then-else takes on your computer. apparently for mine if/then/else is only 2ms while switch takes 5ms... perhaps I should be using if more often!!
Re: Fastest way to cycle through JavaScript comparisons?
Posted: Thu Nov 19, 2009 9:43 am
by jackpf
Probably, but you're not going to notice the difference unless you're running it thousands of times...
Re: Fastest way to cycle through JavaScript comparisons?
Posted: Thu Nov 19, 2009 10:05 am
by Wolf_22
Thanks for the quick replies people. I was just reading an article over
here and saw two little lines of JavaScript code that I believe are supposed to test the amount of time it takes to process something. The lines I'm referring to are the following:
Code: Select all
var start = (new Date).getTime();
/* Run a test. */
var diff = (new Date).getTime() - start;
The way I understand it, the variable takes a time amount before and simply does a difference at the end of the test.
How accurate is this approach for testing speed?
Re: Fastest way to cycle through JavaScript comparisons?
Posted: Thu Nov 19, 2009 10:08 am
by iankent
Reasonably accurate, and a lot more accurate the higher number of times the test is run.
The inaccuracy of the test at small numbers comes from the assignment of the two times - i.e., the length of time it takes to assign the current time to the start and end time variables. the more times the test is run in the middle, the higher the accuracy as the two time assignments don't make up as much of the time accounted for, if that makes sense
Re: Fastest way to cycle through JavaScript comparisons?
Posted: Thu Nov 19, 2009 10:18 am
by Wolf_22
I think I see what you're saying. Makes sense.
