Performance on local constants?

Paddy paddy3118 at googlemail.com
Sat Dec 22 06:56:43 EST 2007


On Dec 22, 10:53 am, William McBrine <wmcbr... at users.sf.net> wrote:
> Hi all,
>
> I'm pretty new to Python (a little over a month). I was wondering -- is
> something like this:
>
> s = re.compile('whatever')
>
> def t(whatnot):
>     return s.search(whatnot)
>
> for i in xrange(1000):
>     print t(something[i])
>
> significantly faster than something like this:
>
> def t(whatnot):
>     s = re.compile('whatever')
>     return s.search(whatnot)
>
> for i in xrange(1000):
>     result = t(something[i])
>
> ? Or is Python clever enough to see that the value of s will be the same
> on every call, and thus only compile it once?
>
> --
> 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0 -- pass it on

Python RE's do have a cache but telling it to compile multiple times
is going to take time.

Best to do as the docs say and compile your RE's once before use if
you can.

The timeit module: http://www.diveintopython.org/performance_tuning/timeit.html
will allow you to do your own timings.

- Paddy.



More information about the Python-list mailing list