startswith( prefix[, start[, end]]) Query
Bruno Desthuilliers
bruno.42.desthuilliers at wtf.websiteburo.oops.com
Fri Sep 7 03:49:29 EDT 2007
Steve Holden a écrit :
> TheFlyingDutchman wrote:
>>> Else, you could as well write your own testing function:
>>>
>>> def str_starts_with(astring, *prefixes):
>>> startswith = astring.startswith
>>> for prefix in prefixes:
>>> if startswith(prefix):
>>> return true
>>> return false
>>>
>>
>> What is the reason for
>> startswith = astring.startswith
>> startswith(prefix)
>>
>> instead of
>> astring.startswith(prefix)
>>
> It's an optimization: the assigment creates a "bound method" (i.e. a
> method associated with a specific string instance) and avoids having to
> look up the startswith method of astring for each iteration of the inner
> loop.
>
> Probably not really necessary, though, and they do say that premature
> optimization is the root of all evil ...
I wouldn't call this one "premature" optimization, since it doesn't
change the algorithm, doesn't introduce (much) complication, and is
proven to really save on lookup time.
Now I do agree that unless you have quite a lot of prefixes to test, it
might not be that necessary in this particular case...
More information about the Python-list
mailing list