which one is more efficient

Michael Spencer mahs at telcopartners.com
Sat Feb 9 02:06:37 CET 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 easily find out yourself, using the timeit module.  Here are some 
examples to get you started:

# succeeding cases
$ python -mtimeit -s"t='D'" "if t == 'D' or t == 'E': pass"
1000000 loops, best of 3: 0.244 usec per loop
$ python -mtimeit -s"t='D'; import re" "if re.search('D|E', t): pass"
100000 loops, best of 3: 5.61 usec per loop

# failing cases
$ python -mtimeit -s"t='F'" "if t == 'D' or t == 'E': pass"
1000000 loops, best of 3: 0.399 usec per loop
$ python -mtimeit -s"t='F'; import re" "if re.search('D|E', t): pass"
100000 loops, best of 3: 4.47 usec per loop

#-> re is much worse whether or not the test succeeds



# try precompiling the re
$ python -mtimeit -s"t='D'; import re; patt = re.compile('D|E')" "if 
patt.search(t): pass"
1000000 loops, best of 3: 1.93 usec per loop
#-> re still worse

# perhaps faster
$ python -mtimeit -s"t='D'" "if t in 'DE': pass"
1000000 loops, best of 3: 0.204 usec per loop

HTH,
Michael





More information about the Python-list mailing list