[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.python

Re: which one is more efficient

Michael Spencer

2/9/2008 1:07:00 AM

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


3 Answers

Bearophile

2/9/2008 10:08:00 AM

0

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

That may be faster indeed, but it gives true if t is "DE" too, and
that may be bad.
The new string search done by Effbot is really good :-)

Bye,
bearophile

Steven D'Aprano

2/9/2008 11:57:00 AM

0

On Sat, 09 Feb 2008 02:08:15 -0800, bearophileHUGS wrote:

> The new string search done by Effbot is really good :-)


Care to explain what "new string search" you're referring to? Inquiring
minds want to know.



--
Steven

Bearophile

2/11/2008 12:39:00 PM

0

Steven D'Aprano:
bearophile:
> > The new string search done by Effbot is really good :-)
> Care to explain what "new string search" you're referring to? Inquiring
> minds want to know.

I meant this good work you can find in Python 2.5:
http://effbot.org/zone/str...

Bye,
bearophile