In Python, why is code running faster in a function than in a global one? Use dis. dis to view the function. The local variable is LOAD_FAST, which is faster than LOAD_GLOBAL.
================
Assume that the dictionary used to query variables is faster when the function is executed internally than the global one. Or another reason, the dictionary of variables may be used internally in the function, it may have better locality and speed in the memory arrangement.
>>> 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':
, 'c': [], 'b': 'abc', '__builtins__':
, '__package__': None, '__name__': '__main__', '__doc__': None}
In addition, dict memory usage is related to the number of nodes.
>>> a = {}>>> for idx in range(50):... 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 104820 104821 104822 335223 335224 335225 335226 335227 335228 335229 335230 335231 335232 335233 335234 335235 335236 335237 335238 335239 335240 335241 335242 335243 335244 335245 335246 335247 335248 335249 3352