1

Possible Duplicate:
Javascript switch vs. if…else if…else

just curious if things will run faster or be laid out in cache nicer or something that might increase performance by using a switch? At very least I know it looks nice and allows the next code to see that all the next sequential statements are dependent upon the evaluation of the same variable.

Community
  • 1
  • 1
vternal3
  • 355
  • 2
  • 17

1 Answers1

3

In general, switch is faster than if - else if statements.

However, kind of best practice is to use if - else if if you got max 3 conditionals. If you're going beyond that, you should use switch statements.

The problem with if else is that it possibly needs to check multiple times before it finally reaches the code to execute. Therefore you also need to optimize the order for your conditional statements.

if( foo ) {
}
else if( bar ) {
}
else if( baz ) {
}

That code would not make much sense from a performance prospective if you expect baz to be true and foo/bar to be false most of the times.

jAndy
  • 212,463
  • 51
  • 293
  • 348