Which is faster?

Aldo Cortesi aldo at nullcube.com
Thu Jan 27 03:58:59 CET 2005


Thus spake Aggelos I. Orfanakos (aorfanakos at gmail.com):

> Any idea which of the following is faster?
> 
> 'a/b/c/'[:-1]
> 
> or
> 
> 'a/b/c/'.rstrip('/')
> 
> Thanks in advance.
> 
> P.S. I could time it but I thought of trying my luck here
> first, in case someone knows already, and of course the
> reason.

Expecting other people to do something simply because you
couldn't be bothered to do it yourself is not polite... That
said, here are the timings on my system:


> python ./timeit.py "'a/b/c/'[:-1]"
1000000 loops, best of 3: 0.511 usec per loop


> python ./timeit.py "'a/b/c/'.rstrip('/')"
1000000 loops, best of 3: 1.3 usec per loop


As you can see, this suggests that the list access method is
quicker. This is to be expected, since the two methods don't
do the same thing - rstrip will return a copy of your string
with any number of trailing '/'es removed. If there aren't
any, it will return the string as-is. The string access
method will always chop exactly one character off the end.
Even though the results for your specific input are the
same, rstrip is a more complex, and therefore slower, beast.



Cheers,



Aldo




-- 
Aldo Cortesi
aldo at nullcube.com
http://www.nullcube.com
Off: (02) 9283 1131
Mob: 0419 492 863



More information about the Python-list mailing list