Comment

R. David Murray

In your tests, the Python function call overhead probably swamped any difference in the performance of the code inside the functions.

Replies

Peter Bengtsson

Swamped?

R. David Murray

python -m timeit -r 10 -s "def myfunc(x): return x[:10]" "myfunc('abcdefg')"
100000 loops, best of 10: 2.75 usec per loop

./python -m timeit -r 10 "'abcdefg'[:10]"
1000000 loops, best of 10: 0.714 usec per loop

0.714 is 25% of 2.75. So "swamped" might appear to be an overstatement. ("Overwhelm with an excessive amount of something"). However, even with -r 10 I'm getting measurements for the smaller numbers that vary by as much as 50%, so I think swamped is probably appropriate. Better measurements could doubtless be obtained if one had access to a test machine that wasn't doing anything else (I'm measuring on my laptop).

Some additional measurments:
rdmurray@hey:~/python/p33>./python -m timeit -r 10 "'abcdefg'[:3]"
1000000 loops, best of 10: 1.41 usec per loop
rdmurray@hey:~/python/p33>./python -m timeit -r 10 "'abcdefg'[:3]"
1000000 loops, best of 10: 1.41 usec per loop
rdmurray@hey:~/python/p33>./python -m timeit -r 10 "'abcdefg'[:3]"
1000000 loops, best of 10: 1.42 usec per loop
rdmurray@hey:~/python/p33>./python -m timeit -r 10 "'abcdefg'[:10]"
1000000 loops, best of 10: 0.633 usec per loop
rdmurray@hey:~/python/p33>./python -m timeit -r 10 "'abcdefg'[:10]"
1000000 loops, best of 10: 0.714 usec per loop
rdmurray@hey:~/python/p33>./python -m timeit -r 10 "'abcdefg'[:10]"
1000000 loops, best of 10: 0.696 usec per loop
rdmurray@hey:~/python/p33>./python -m timeit -r 10 "'abcdefg'[:10]"
1000000 loops, best of 10: 0.319 usec per loop
rdmurray@hey:~/python/p33>./python -m timeit -r 10 "'abcdefg'[:3]"
1000000 loops, best of 10: 1.35 usec per loop

So, it looks like the slice is indeed faster if longer than the string on CPython (my measurements were on my current checkout of 3.3, by the way). That, however, is a (current) CPython implementation artifact, and not something on which to rely (possibly outside of tuning a particular application for a particular machine/environment).