[Python-Dev] Switch statement
Josiah Carlson
jcarlson at uci.edu
Mon Jun 19 03:56:01 CEST 2006
Thomas Lee <tom at vector-seven.com> wrote:
> I see. But restricting the switch to constants in the name of
> performance may not make sense in a language like Python. Maybe this is
> something for the PEP to discuss, but it seems such an implementation
> would be confusing and sometimes it may not be possible to use a switch
> case in place of if/elif/else statements at all.
The PEP already discussed it. Offering arbitrary expressions whose
meaning can vary at runtime would kill any potential speedup (the
ultimate purpose for having a switch statement), leaving us with
if/elif/else that, paradoxically, ran faster in general than the
equivalent switch statement.
[snip]
> a) unnecessarily duplication of constant values for the purpose of using
> them as case values
The vast majority of use-cases in C/C++ uses single character or small
integer constants. This hasn't slowed down the switch/case use in C/C++,
and I haven't even seen an over-abundance of const or macro definitions
of constants in C/C++ switch/case statements.
> I do get the distinction, I'm just wondering if the usefulness of the semantics
> (or lack thereof) are going to negate any potential performance
> enhancements: if a switch statement is never used because it's only
> useful in a narrow set of circumstances, then maybe we're looking to
> improve performance in the wrong place?
Please re-read the PEP, more specifically the 'Problem' section:
"A nice example of this is the state machine implemented in
pickle.py which is used to serialize Python objects. Other
prominent cases include XML SAX parsers and Internet protocol
handlers."
> Just thinking about it, maybe there could be two different code paths
> for switch statements: one when all the case values are constants (the
> 'fast' one) and one where one or more are expressions. This would mean a
> slightly longer compile time for switch statements while ensuring that
> runtime execution is the maximum possible without placing any major
> restrictions on what can be used as a case value.
The non-fast version couldn't actually work if it referenced any names,
given current Python semantics for arbitrary name binding replacements.
- Josiah
More information about the Python-Dev
mailing list