Python字节码编译器;删除不必要的变量?
考虑到以下情况:
def foo():
x = a_method_returning_a_long_list()
y = a_method_which_filters_a_list(x)
return y
Python 的字节码编译器会保留 x
& 吗? y
在内存中,或者它是否足够聪明,可以将其简化为以下内容?
def foo():
return a_method_which_filters_a_list(a_method_returning_a_long_list())
Given the following:
def foo():
x = a_method_returning_a_long_list()
y = a_method_which_filters_a_list(x)
return y
will Python's bytecode compiler keep x
& y
in memory, or is it clever enough to reduce it to the following?
def foo():
return a_method_which_filters_a_list(a_method_returning_a_long_list())
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
它将 x 和 y 保留在内存中:
整个操作非常高效,因为它是使用
LOAD_FAST
和STORE_FAST
代码完成的。正如 Roadrunner-EX 在其中一条评论中所说,两个版本的
foo
使用的内存量基本相同,如x
和y 只是结果的引用(即指针)。
It keeps x and y in memory:
The whole operation is quite efficient, as it is done using the
LOAD_FAST
andSTORE_FAST
codes.As Roadrunner-EX remarks in one of the comments, the amount of memory used by your two versions of
foo
is basically the same, asx
andy
are just references (i.e., pointers) to the results.所以看起来这两个变量是分开保存的。
So it looks like both variables are held separately.
我不确定,但我猜这会让它们留在记忆中,原因有两个。首先,这样做可能付出的努力超过了其价值。无论哪种方式,都不会有巨大的性能变化。其次,变量 x 和 y 本身可能占用内存(以指针/引用的形式),由于赋值的显式性质,编译器不会触及这些内存。
I'm not certain, but I would guess it would keep them in memory, for 2 reasons. First, it's probably more effort than its worth to do that. There wouldn't be a huge performance change either way. And second, the variables x and y are probably themselves taking up memory (in the form of pointers/references), which the compiler would not touch, due to the explicit nature of the assignment.