which one is more efficient
Gabriel Genellina
gagsl-py2 at yahoo.com.ar
Fri Feb 8 20:21:32 EST 2008
En Fri, 08 Feb 2008 22:45:06 -0200, ki lo <kilo8257 at gmail.com> escribió:
> 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.
Use the timeit module to measure the various alternatives:
http://docs.python.org/lib/module-timeit.html
Remember to test both cases, success and failure. I bet that using re is
terribly slow.
Note: better to avoid `type` as a variable name, it's a builtin type
itself.
python -m timeit -s "typ='E'" "typ =='D' or typ == 'E'"
python -m timeit -s "typ='X'" "typ =='D' or typ == 'E'"
python -m timeit -s "typ='E'" "typ in 'DE'"
python -m timeit -s "typ='E';valid='DE'" "typ in valid"
python -m timeit -s "typ='E';valid=tuple('DE')" "typ in valid"
python -m timeit -s "typ='E';valid=set('DE')" "typ in valid"
valid.find(typ)>=0
re.match("D|E", typ)
--
Gabriel Genellina
More information about the Python-list
mailing list