...

View Full Version : if statment or Conditional OP faster?



sitNsmile
04-01-2010, 06:05 PM
Okay, I know the mark must be extremely small to test, but I notice the "Conditional operator" slightly use less php memory.

which here is my test;




if($orderType=='DESC'){$orderType='DESC';}
elseif($orderType=='ASC'){$orderType='ASC';}
else{$orderType='ASC';}


or (Conditional operator)


$orderType = $oType == 'DESC' ? 'DESC' : 'ASC' ;

Same type of idea, just using a different method. but as building larger application, speed and resources are critical.


also just realized could use the "switch/case" in this test as well.



switch($oType)
{
case 'DESC':$orderType = 'DESC';break;
case 'ASC':$orderType = 'ASC';break;
}

Which you rather use? if statement yes is easier to read.

Fou-Lu
04-01-2010, 06:14 PM
The conditional expression versus the ternary is debatable. This is one of those ones where you shouldn't be able to notice a difference in either case.
If you have a single if/else (which that should be, there is no need for an else if in there), the Ternary will be faster. However, it is more difficult to add additional checks, since you need to chain the ternary: (conditional) ? ((conditional) ? true : false) : ((conditional) ? true : false) so it becomes difficult to read.
The best choice if expansion is possible is to use a switch which is faster than an if/else check. This is especially true if you want to allow multiple if's to result in the same result, but is not useful if you're using datatype checking since it uses loose comparisons (== and never === checks). Unlike an if/elseif/else pair, the switch can potentially use more memory and time if you never break.

sitNsmile
04-01-2010, 06:31 PM
The conditional expression versus the ternary is debatable. This is one of those ones where you shouldn't be able to notice a difference in either case.
If you have a single if/else (which that should be, there is no need for an else if in there), the Ternary will be faster. However, it is more difficult to add additional checks, since you need to chain the ternary: (conditional) ? ((conditional) ? true : false) : ((conditional) ? true : false) so it becomes difficult to read.
The best choice if expansion is possible is to use a switch which is faster than an if/else check. This is especially true if you want to allow multiple if's to result in the same result, but is not useful if you're using datatype checking since it uses loose comparisons (== and never === checks). Unlike an if/elseif/else pair, the switch can potentially use more memory and time if you never break.

Thanks yeah, makes a lot of sense. I used to use if/else so much, so working on moving into other methods, and tired of Procedural code, getting more into OOP with new projects.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum