using Dis.dis to view functions, local variables are load_fast, faster than Load_global
============
Guess, when executing inside a function, the dictionary used to query the variable is smaller than the global case, so it is faster, or for another reason, a dictionary of variables may be used inside the function, which may have better locality in memory arrangement and can be faster.
>>> def do_test (): ... A = 1 ... b = ' abc ' ... c = [] ... Print locals () ... >>> do_test () {' A ': 1, ' C ': [], ' B ': ' abc '}>>> >>> a = 1>>> b = ' abc ' >>> C = []>>> Print locals () {' A ': 1, ' do_test ': <function do_test at 0x7fab08be8410> ' C ': [], ' B ' : ' abc ', ' __builtins__ ': <module ' __builtin__ ' (built-in);, ' __package__ ': None, ' __name__ ': ' __main__ ', ' __doc__ ' : None}
In addition, about Dict occupies memory, and the number of nodes related
>>> a = {}>>> for idx in range: ... Print idx, sys.getsizeof (a) ... A[IDX] = idx ... 0 2801 2802 2803 2804 2805 2806 10487 10488 10489 104810 104811 104812 104813 104814 104815 104816 104817 104818 104819 10 4820 104821 104822 335223 335224 335225 335226 335227 335228 335229 335230 335231 335232 335233 335234 335235 335236 33523 7 335238 335239 335240 335241 335242 335243 335244 335245 335246 335247 335248 335249 3352