which one is faster?
Antoine Pitrou
solipsis at pitrou.net
Fri Jan 29 06:48:26 EST 2010
Le Thu, 28 Jan 2010 22:39:32 -0800, alex23 a écrit :
> 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?
>
[...]
>
>>From the looks of those results, using 'in' seems to be the fastest.
To answer the question more precisely:
* "in" is the fastest because it doesn't have the method call overhead.
This is only a fixed cost, though, and doesn't depend on the inputs.
* all four alternatives use the same underlying algorithm, *but* count()
has to go to the end of the input string in order to count all
occurrences. The other expressions can stop as soon as the first
occurence is found, which can of course be a big win if the occurrence is
near the start of the string and the string is very long
So, to sum it up:
* "in" is faster by a small fixed cost advantage
* "find" and "index" are almost exactly equivalent
* "count" will often be slower because it can't early exit
Regards
Antoine.
More information about the Python-list
mailing list