which one is faster?
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.index(targetStr) with exception
> 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 : t = 'foo'
In : s =
In : timeit s.find(t)
1000000 loops, best of 3: 374 ns per loop
In : timeit s.index(t)
1000000 loops, best of 3: 381 ns per loop
In : timeit s.count(t)
1000000 loops, best of 3: 397 ns per loop
In : 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