Home  >  Article  >  Backend Development  >  Python 中,代码放在函数中运行为什么比放在全局中运行快?

Python 中,代码放在函数中运行为什么比放在全局中运行快?

PHP中文网
PHP中文网Original
2016-06-06 16:11:061076browse

用dis.dis查看函数,局部变量是LOAD_FAST,要比LOAD_GLOBAL要快

============
猜想一下,在函数内部执行的时候,查询变量所用的字典,比全局情况下要小,所以更快;或者另一个原因,可能函数内部时使用变量的字典,可能在内存排列上有更好的局部性,也能更快。

>>> 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', '__built
ins__': , '__package__': None, '__name__': '__main__', '__doc__': None}

另外,关于dict占用内存,和节点数量相关

>>> a = {}
>>> for idx in range(50):
...     print idx, sys.getsizeof(a)
...     a[idx] = idx
... 
0 280
1 280
2 280
3 280
4 280
5 280
6 1048
7 1048
8 1048
9 1048
10 1048
11 1048
12 1048
13 1048
14 1048
15 1048
16 1048
17 1048
18 1048
19 1048
20 1048
21 1048
22 3352
23 3352
24 3352
25 3352
26 3352
27 3352
28 3352
29 3352
30 3352
31 3352
32 3352
33 3352
34 3352
35 3352
36 3352
37 3352
38 3352
39 3352
40 3352
41 3352
42 3352
43 3352
44 3352
45 3352
46 3352
47 3352
48 3352
49 3352


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn