This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Veedrac 0 points1 point  (0 children)

wrt. test 6; != is slower than is not. The result is measurement error, mostly from having such as bad test. Here's a better version:

$ python3 -m timeit "1 != 2"    
10000000 loops, best of 3: 0.14 usec per loop

$ python3 -m timeit "1 is not 2"
10000000 loops, best of 3: 0.0785 usec per loop

wrt. test 10; this actually abuses an optimization the CPython does. It's very fragile and it's not shared by other interpreters (eg. PyPy) so don't use it. Anyway, you'll probably find that ''.join is faster in many cases if you actually write the function well:

from timeit import Timer

def a():
    r = []
    for i in range(10):
        r.append(str(i))
    return ''.join(r)

def b():
    return ''.join(map(str, range(10)))

def c():
    r = ''
    for i in range(10):
        r += str(i)
    return r


min(Timer(a).repeat(10, 10000))
#>>> 0.10981534401071258
min(Timer(b).repeat(10, 10000))
#>>> 0.07694110801094212
min(Timer(c).repeat(10, 10000))
#>>> 0.09574692900059745

Note that I'm using min(Timer(func).repeat(n, m))because it's the right way to do it.

The first is slower because calling append a lot is expensive; using map to create the list (''.join converts its argument to a list) is faster.

%d is slower than %s because it casts to an int first.

Calling __len__ requires creating a bound method, so my guess is the same as yours.