Which is faster?
Terry Reedy
tjreedy at udel.edu
Thu Jan 27 00:44:49 EST 2005
"Aggelos I. Orfanakos" <aorfanakos at gmail.com> wrote in message
news:1106793602.782397.61260 at z14g2000cwz.googlegroups.com...
> Any idea which of the following is faster?
>
> 'a/b/c/'[:-1]
> 'a/b/c/'.rstrip('/')
I find the first easier to read and mentally process. Others may have a
different answer. But perhaps you meant with the CPython 2.x
implementation ;-)
> 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.
For more on the CPython (2.2) reason, consider
>>> def f1(s): return s[:-1]
...
>>> def f2(s): return s.rstrip('/')
...
>>> import dis
>>> dis.dis(f1)
0 SET_LINENO 1
3 SET_LINENO 1
6 LOAD_FAST 0 (s)
9 LOAD_CONST 1 (-1)
12 SLICE+2
13 RETURN_VALUE
14 LOAD_CONST 0 (None)
17 RETURN_VALUE
>>> dis.dis(f2)
0 SET_LINENO 1
3 SET_LINENO 1
6 LOAD_FAST 0 (s)
9 LOAD_ATTR 1 (rstrip)
12 LOAD_CONST 1 ('/')
15 CALL_FUNCTION 1
18 RETURN_VALUE
19 LOAD_CONST 0 (None)
The second has a load attribute (via dict lookup) that the first does not.
More important, the second has a generic function call versus a specific
byte-coded slice call. The rstrip will also do a slice after it determines
the endpoint of the slice.
Terry J. Reedy
More information about the Python-list
mailing list