November 14, 2009 - 10:48 pm
How is it the same and different as an if/else if statement?
If statements are designed to select one of two branches. While that can be chained to select from more than two branches, it gets complex and hard to read. The select statement chooses from numerous branches.
If calculates the value of a logical expression. This logical expression may be very complex, but will evaluate to true or false.
Select calculates the value of an expression and then compares the result with a set of constants. The matching constant selects the branch to use.
If you have to select one of many branches it’s more efficient to use the select statement. It’s also much easier to read. If you have multiple options it’s better to express that directly rather than chaining if statements.
Writing code that is easy to understand is very important. Everything you can do to make the intention clearer is worthwhile.
The system can often use smarter comparisons rather than something like "is it 1? no. Is it 2? no. Is it 3? no …"