Python import X 还是 from X import Y?(表现) [英] Python import X or from X import Y? (performance)
问题描述
如果有一个库,我将使用至少两种方法,以下在性能或内存使用方面有什么不同吗?
If there is a library from which I'm going to use at least two methods, is there any difference in performance or memory usage between the following?
from X import method1, method2
和
import X
推荐答案
有区别,因为在 import x
版本中有两个名称查找:一个用于模块名称,第二个为函数名;另一方面,使用 from x import y
,您只有一次查找.
There is a difference, because in the import x
version there are two name lookups: one for the module name, and the second for the function name; on the other hand, using from x import y
, you have only one lookup.
使用 dis 模块可以很好地看到这一点:
You can see this quite well, using the dis module:
import random
def f_1():
random.seed()
dis.dis(f_1)
0 LOAD_GLOBAL 0 (random)
3 LOAD_ATTR 0 (seed)
6 CALL_FUNCTION 0
9 POP_TOP
10 LOAD_CONST 0 (None)
13 RETURN_VALUE
from random import seed
def f_2():
seed()
dis.dis(f_2)
0 LOAD_GLOBAL 0 (seed)
3 CALL_FUNCTION 0
6 POP_TOP
7 LOAD_CONST 0 (None)
10 RETURN_VALUE
如您所见,使用 from x import y
形式会更快一些.
As you can see, using the form from x import y
is a bit faster.
另一方面,import x
比 from x import y
便宜,因为名称查找更少;让我们看看反汇编的代码:
On the other hand, import x
is less expensive than from x import y
, because there's a name lookup less; let's look at the disassembled code:
def f_3():
import random
dis.dis(f_3)
0 LOAD_CONST 1 (-1)
3 LOAD_CONST 0 (None)
6 IMPORT_NAME 0 (random)
9 STORE_FAST 0 (random)
12 LOAD_CONST 0 (None)
15 RETURN_VALUE
def f_4():
from random import seed
dis.dis(f_4)
0 LOAD_CONST 1 (-1)
3 LOAD_CONST 2 (('seed',))
6 IMPORT_NAME 0 (random)
9 IMPORT_FROM 1 (seed)
12 STORE_FAST 0 (seed)
15 POP_TOP
16 LOAD_CONST 0 (None)
19 RETURN_VALUE
我不知道原因,但看起来from x import y
形式看起来像一个函数调用,因此比预期的更昂贵;因此,如果导入的函数只使用一次,则意味着使用 import x
会更快,而如果多次使用,则使用 会更快从 x 导入 y
.
I do not know the reason, but it seems the form from x import y
looks like a function call, and therefore is even more expensive than anticipated; for this reason, if the imported function is used only once, it means it would be faster to use import x
, while if it is being used more than once, it becomes then faster to use from x import y
.
也就是说,像往常一样,我建议您不要遵循这些知识来决定如何导入模块和函数,因为这只是一些过早的优化.
就我个人而言,我认为在很多情况下,显式命名空间更具可读性,我建议您也这样做:使用您自己的审美 :-)
That said, as usual, I would suggest you not following this knowledge for your decision on how to import modules and functions, because this is just some premature optimization.
Personally, I think in a lot of cases, explicit namespaces are much more readable, and I would suggest you doing the same: use your own sense of esthetic :-)
这篇关于Python import X 还是 from X import Y?(表现)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!