0

Imagine, that you have a variable called $varName. It can take one of two values: 'aaa' or 'bbb'. So, which statement will be optimal and why?

1)

if ($varName === 'aaa') {
/* Code for 'aaa' */
} else {
/* Code for 'bbb' */
}

2)

if ($varName === 'bbb') {
/* Code for 'bbb' */
} else {
/* Code for 'aaa' */
}

3)

if ($varName == 'aaa') {
/* Code for 'aaa' */
} else {
/* Code for 'bbb' */
}

4)

if ($varName == 'bbb') {
/* Code for 'bbb' */
} else {
/* Code for 'aaa' */
}

UPD: Variable take 'aaa' value more ofter than 'bbb'

lezhni
  • 292
  • 2
  • 12

1 Answers1

1

If you know for sure $varName gets the (string) "aaa" more often then option (1) would be optimal for two reasons:

  1. Operator "===" does not convert the data. See this answer for more details.
  2. The code will proceed to the else part less often.

PS. The performance differences are insignificant, it is much more about readability.

Community
  • 1
  • 1
Filip Juncu
  • 352
  • 2
  • 10
  • Not knowing PHP internals, I beleave that, unless the method exits on the final of the "implicit then", jump to the else code would have exactly same result. Why: on condition true, continue the flow without jump, but jump the else code, if false jump the "implicit then" code directly to the else, but no jump at the end. So, you always get a jump when using if, the only difference is *when* the jump occurs. May be this got broken for example with optimization. So (1) and (2) should be equivalent. – fbiazi Nov 28 '15 at 15:05