2010-07-25, 12:36 PM
buddyseeker Wrote:uuum, off topic: I'm sure there's a pros and cons when using 'if' and 'switch' statement right?Always begin writing code in a style that has the best readability first, optimization comes last.
In terms of performance, switch statements has the advantage of comparing multiple values to the same value over and over again. This task is trivial in machine code and the compiler will take advantage of that. "If / else if" statements do not restrict comparison to a single value against multiple values. When turned into machine code, each comparison would require loading a different value into the registers before comparing the registers, whereas the switch statement only loads the value to be checked into the register once at the beginning and reuses it to compare to other values.
Then again, if you're using "if / else if" blocks in a way that always compare the same variable to other values, modern compilers are smart enough to optimize it into the same code that you would have gotten with a switch statement anyway. So, go with whichever one that gives the best readability according to situation.

