devork

E pur si muove

re.search() faster then re.match()

Sunday, December 19, 2010

This is a counter-intuitive discovery, in IPython:


In [18]: expr = re.compile('foo')

In [19]: %timeit expr.search('foobar')
1000000 loops, best of 3: 453 ns per loop

In [20]: %timeit expr.match('foobar')
1000000 loops, best of 3: 638 ns per loop

So now I'm left wondering why .match() exists at all. Is it really such a common occurrence that it's worth an extra function/method?

Just to be complete, if this is actually what you want there is no performance gap:


In [25]: expr = re.compile('^foo')

In [26]: %timeit expr.search('foobar')
1000000 loops, best of 3: 617 ns per loop

In [27]: %timeit expr.match('foobar')
1000000 loops, best of 3: 612 ns per loop
Sunday, December 19, 2010 |

0 comments:

New comments are not allowed.

Subscribe to: Post Comments (Atom)