case/switch statement?

Peter Hansen peter at engcorp.com
Sun Jun 12 17:19:06 EDT 2005


Steven D'Aprano wrote:
> On Sat, 11 Jun 2005 19:47:58 -0500, Skip Montanaro wrote:
>>If the case values are constants known to the compiler, it can generate O(1)
>>code to take the correct branch.
>>It is precisely this behavior that is desired in many situations.  
> 
> Agreed. I certainly don't object to sensible optimizations! But the number
> of if...elif statements which can be optimised are a vanishingly small
> subset of the number of possible if...elif statements.
> 
> And you can bet your last dollar that many people will use case statements
> even when doing so gives no advantage, in a mistaken opinion that it will
> be somehow magically faster.

Case statements are actually more suitable in many cases even when 
performance is not a goal for reasons of *readability*.

When reading an if statement, you have to scan down through effective 
each statement attempting to find the case in which you are interested. 
  Some cases can be compound.  The nested ifs can get confused with the 
surrounding ones (in Python or a language with explicit block 
delimiters).  The cases are often not written in any particular order, 
or they are ordered *for* performance reasons, but in ways that make it 
harder to "scan".

A case statement, on the other hand, can be a message from the 
programmer, saying in effect "here's code that represents a series of 
_simple_ conditionals, ordered (usually) in a sensible way (e.g. 
ascending numerical order), so just jump to the case you want and carry 
on maintaining this nice code."

In current Python the equivalent approach is, of course, a dictionary of 
some kind, though it's arguable whether this is as clean in many cases 
as a case statement would be.

-Peter



More information about the Python-list mailing list