which one is faster?

alex23 wuwei23 at gmail.com
Fri Jan 29 07:39:32 CET 2010


On Jan 29, 4:29 pm, "Stephen.Wu" <54wut... at gmail.com> wrote:
> str.find(targetStr)
> str.index(targetStr) with exception
> str.count(targetStr)
> targetStr in str
>
> which is the fastest way to check whether targetStr is in str?

It's generally a lot quicker to investigate this kind of question
yourself using the interpreter & the timeit module. You'll need skills
like these to be able to profile your code to look for actual
performance bottlenecks, generic advice on the fastest of a set of
functions will only get you so far.

IPython is pretty handy for simple timing tests as it provides
convenience wrappers around timeit:

In [1]: t = 'foo'
In [2]: s =
'djoemdmsllsodmedmsoskemozpleaoleodspsfooosoapxooeplaapakekoda'
In [3]: timeit s.find(t)
1000000 loops, best of 3: 374 ns per loop
In [4]: timeit s.index(t)
1000000 loops, best of 3: 381 ns per loop
In [7]: timeit s.count(t)
1000000 loops, best of 3: 397 ns per loop
In [8]: timeit t in s
1000000 loops, best of 3: 219 ns per loop

>From the looks of those results, using 'in' seems to be the fastest.



More information about the Python-list mailing list