The speed of global and local variables in Python

I think everyone knows that:

Python accesses local variables much more efficiently than global variables

Ok, this is true:

oldlist = [str(i) for i in range(500)] oldlist1 = [i for i in range(500)] %%timeit newlist = [] for word in oldlist: newlist.append(word.upper()) 

10,000 cycles, best 3: 178 μs per loop

 %%timeit def func(): newlist = [] for word in oldlist: newlist.append(word.upper()) return newlist newlist = func() 

10,000 cycles, best of 3: 93.2 μs per loop

Unfortunately, it seems that this is not a global rule, but a special case:

 %%timeit newlist = [] for nr in oldlist1: newlist.append(nr * nr) 

10,000 cycles, best of 3: 60.3 μs per loop

 %%timeit def func(): newlist = [] for nr in oldlist1: newlist.append(nr * nr) return newlist newlist = func() 

10,000 cycles, best 3: 60.5 μs per loop

How to explain these tests?

+6
source share
1 answer

In the last example, you first define an additional function. If you start the timer after searching for a function, it will be faster.

+1
source

Source: https://habr.com/ru/post/958403/


All Articles