YunliuStorage
YunliuStorage

Reputation: 489

Python 3.5, using a declared variable is slower compared to using its value directly?

Option 1:

b = 1
for i in range(1000000):
    a = b in {1, 2, 3, 4, 5}

Option 2:

b = 1
c = {1, 2, 3, 4, 5}
for i in range(1000000):
    a = b in c

Option 1 is faster than Option 2, I would thought Option2 should be faster. Does this have anything to do with stack or heaps? or is this about how python optimize its loops? or is it a dictionary namespace related?

I am asking this because usually option2, the slower version, is a better coding practice. Option1 is way too hardcoded.

Upvotes: 0

Views: 211

Answers (1)

Reblochon Masque
Reblochon Masque

Reputation: 36662

There is no noticeable difference, most probably because of caching of the results and other compile time optimizations.

But is you take the results of the slowest runs as significant (maybe they are?), it seems that the second one's slowest run is 3 to 4 times slower than the first. (maybe it is the true speed of execution before anything gets cached and optimized? IDK)

The first one:

%%timeit
def f1(b, c):
    for i in range(1000000):
        a = b in c

result:

The slowest run took 30.16 times longer than the fastest. This could mean that an intermediate result is being cached.
10000000 loops, best of 3: 123 ns per loop

The second one:

%%timeit
def f2(b):
    for i in range(1000000):
        a = b in {1, 2, 3, 4, 5}

result:

The slowest run took 8.05 times longer than the fastest. This could mean that an intermediate result is being cached.
10000000 loops, best of 3: 126 ns per loop

ipython 3.4.4, anaconda, in Jupyter notebook, on an oldish macbook air

Upvotes: 1

Related Questions