which one is more efficient

Gary Herron gherron at islandtraining.com
Fri Feb 8 20:01:52 EST 2008


ki lo wrote:
> I have type variable which may have been set to 'D' or 'E'
>
> Now, which one of following statements are more efficient
>
> if type =='D' or type == 'E':
>
> or
>
> if re.search("D|E", type):
>
> Please let me know because the function is going to called 10s of
> millions of times.
>
> Thanks
> Kilo
>
You can answer this question yourself: 
  Write two small test files, one using each test, and then use the
timeit module on each. 

I suspect the first will be much faster -- but I'd not stake any money
on that without running tests first.

However, ... no matter which test is faster -- will it really make much
difference considering that the body of the if may be much more involved
than either test?   This may be an example of optimization-too-early. 
If profiling your final code shows that the differences in the test is a
small fraction of 1% of the total execution time -- then your time would
be better spent worrying about how to optimize the other portions of you
code.

Gary Herron




More information about the Python-list mailing list