0

Here is my code I wanted to ask if there is a better way to do this? I'm going to need more "else if" options and I'm worried about performance

if($_GET['begin'] === 'yeg'){

} else if ($_GET['begin'] === 'deda') {

} else if ($_GET['begin'] === 'beara') {

} else if ($_GET['begin'] === 'eima') {

} else if ($_GET['begin'] === 'aba') {

}
zumbamusic
  • 180
  • 1
  • 2
  • 14
  • 3
    Have a look at : http://php.net/manual/en/control-structures.switch.php –  Jul 25 '14 at 09:59
  • Performance is very much increased in a switch statement as @caCtus linked, as the variable gets evaluated only once and then compared, saving memory and clock cycles. – t3chguy Jul 25 '14 at 10:00
  • 1
    @t3chguy "Performance is _very much_ increased" do you have any benchmarks to suggest that? I don't see how this could be the bottleneck in anything but the most trivial of applications. – Tom Fenech Jul 25 '14 at 10:02
  • @TomFenech Agreed, it's likely a very minor performance increase at best. Premature optimisation springs to mind here. – naththedeveloper Jul 25 '14 at 10:05
  • 1
    bad choice of wording on my part, the increase isn't substantial, maybe after a few hundred ElseIf statements, and in low amounts the ElseIf statements are actually faster. – t3chguy Jul 25 '14 at 10:07

2 Answers2

10

You should use switch statement instead. A switch construct is more easily translated into a jump (or branch) table. This can make switch statements much more efficient than if-else when the case labels are close together. The idea is to place a bunch of jump instructions sequentially in memory and then add the value to the program counter. This replaces a sequence of comparison instructions with an add operation. - @Judge Maygarden Why the switch statement and not if-else?

$begin = $_GET['begin'];

switch ($begin):

case 'yeg':
   //do something
   break;

case 'deda':
   //do something
   break;

case 'beara':
   //do something
   break;

case 'eima':
   //do something
   break;

case 'aba':
   //do something
   break;

endswitch;
Community
  • 1
  • 1
John Robertson
  • 1,486
  • 13
  • 16
0

You can try to use a switch statement instead:

switch ($_GET['begin']) {
    case 'yeg':
        break;

    case 'deda':
        break;

    // Yada yada, continue like this as much as needed.
}
Gladen
  • 792
  • 2
  • 8
  • 17