Forum Moderators: coopster

Message Too Old, No Replies

if else or switch (most efficient?)

long list of conditionals

         

Patrick Taylor

11:24 pm on Dec 14, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Which of the two options is most efficient, server-wise, in terms of speed of processing?

(1)
if (something) {
// action;
} else if (something else) {
// another action;
} etc etc

(2)
switch($var) {
case('something'):
// action;
break;
case('something else'):
// another action;
break;
etc etc
}

Is there a difference? Any advice appreciated.

Patrick

phparion

5:01 am on Dec 15, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



the time execution difference, if any, will be negligible. Switch is a little more organized than IF-ELSE and therefore it is used for long sessions of decision making code. However you can convert every if-else into switch but vice versa is not possible in some cases.

anyway, if you are concerned with the server and execution speed then the execution time difference between these two must be very very small.

Patrick Taylor

1:04 pm on Dec 15, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Many thanks... switch does (somehow) look more efficient.

PHP_Chimp

1:50 pm on Dec 16, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



if/elseif is faster than switch, although not by much. About 0.2 seconds for 20000 items in an array (with the set up that I tested on).
However if you need a default i.e. if/elseif/else then switch is faster by about the same amount.

So if you need and else then use switch default: and it will be very slightly faster. However unless you are actually looping through 1000's of then an increase in speed of 1/10000 second per iteration is not likely to make any difference :)

I prefer switch as it is easier to read. Nothing to do with speed.

Patrick Taylor

2:34 pm on Dec 16, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I'm only looping through thirty or so, and I do need a default if/elseif/else. Thank you for the definitive answer. I'm going to stick with if else on this occasion.

Patrick