0

I check this PHP website benchmark for check switch statement VS if else if statement. And I see this result:

Is a there a difference between switch and if structures?. Call 1'000x

  • 141 % *if and elseif (using ==)* Total time: 165 µsview code
  • 139 % *if, elseif and else (using ==)* Total time: 162 µsview code
  • 110 % *if and elseif (using ===)* Total time: 128 µsview code
  • 100 % *if, elseif and else (using ===)* Total time: 117 µsview code
  • 149 % *switch / caseTotal* time: 174 µsview code
  • 181 % *switch / case / default* Total time: 211 µsview code

In result i see if else if is faster (+ **100 %** *if, elseif and else (using ===)* Total time: 117 µsview code).

This benchmark is true and if, elseif and else (using ===) is better and faster as switch statement?!

2
  • Its no surprise that === is faster than == since == tries to make a type conversion if the two values are not equal. The switch-case-statement had only 2 cases (and a default case). I think it gets faster (relative to if-elseif) if you have more cases. But what exactly is your question? Commented Jul 19, 2015 at 11:30
  • Benchmark flaw: is the first case/if more common or less common than the last? Commented Jul 25, 2015 at 17:26

2 Answers 2

3

Whether you get exactly the same results will vary based on what conditions you are evaluating, your equipment, settings, and other factors. But yes, generally if/elseif/else with strict comparison (===) will outperform switch. The reason is that switch uses "loose" (i.e., type-insensitive) comparison (==), which is slower than type-sensitive comparison (===).

Keep in mind that these differences are extremely tiny and are going to be dwarfed by any inefficiencies in your algorithm. So, you should only tune for details like this after you are sure you have eliminated other major bottlenecks.

Sign up to request clarification or add additional context in comments.

Comments

1

Default PHP switch is not with exact match.

Some examples for exact match switch.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.