Python解释代码优化
考虑下面的代码片段:
dict [name] = 0
dict [name] += 1
dict [name] += 1
Does the python解释器自动识别对字典值的重复引用并使用缓存的本地引用代替?,有点类似于C/C++的别名优化,变成这样:
value = dict [name]
value = 0
value += 1
value += 1
显然,这不是一个大的问题需要手动执行此操作,但我很好奇是否确实有必要。如有任何见解、反馈等,我们将不胜感激。
Consider the following code snippet:
dict [name] = 0
dict [name] += 1
dict [name] += 1
Does the python interpreter automatically recognise the repeated references to the dictionary value and use a cached local reference instead?, somewhat akin to the aliasing optimisations of C/C++, becoming something like so:
value = dict [name]
value = 0
value += 1
value += 1
Obviously, it's not a big deal to do this manually but I'm curious if it's actually necessary. any insight, feedback, etc is appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以通过反汇编程序运行它来找出:
运行我们得到:
在本例中,
LOAD_FAST
看起来正在加载tdict
和的值>name
每次我们尝试访问它来执行增量时,所以答案似乎是否定的。You can run it through the disassembler to find out:
Running this we get:
It looks like, in this case, that
LOAD_FAST
is loading up the values oftdict
andname
each time we try to access it to perform the increment, so the answer would appear to be no.仅仅通过检查代码是不可能实现这种类型的优化的。您的名称
dict
可能不是指本机字典,而是指实现__setitem__
的用户定义对象,并且必须调用该方法三次。在运行时,复杂的实现可以记录名称的实际值,并进行优化,但在运行之前无法在不破坏某些 Python 语义的情况下完成。That type of optimization isn't possible simply by inspecting the code. Your name
dict
could refer not to a native dictionary, but a user-defined object that implements__setitem__
, and that method has to be called three times. At runtime, a sophisticated implementation could note the actual value of the name, and make an optimization, but it can't be done before runtime without breaking some Python semantics.不,因为那行不通,你甚至用你自己的代码证明了这一点——它实际上并不等同:
Python 没有 C 风格的“引用”。您想到的仅适用于可变类型,例如
list
。这是 Python 的一个非常基本的属性,在进行 Python 编程时,您可能应该忘记 C 教给您的有关变量的所有内容。No, because that would not work, and you even demonstated that with your own code - it's actually not equivalent:
Python does not have C-ish "references". What you had in mind would work only for mutable types such as
list
. This is a very fundamental property of Python and you should probably forget everything C taught you about variables when programming Python.将您的两个示例更改为如下所示:
并且
您可以在以下测试中看到,v2 更快,但 pypy 更快:-)
SO:为单个解释器优化代码并不好(我还没有测试 Jython例如...),但是当 有人 优化解释器时就很棒了...
Changing your two examples into something like this:
and
You can see in the following tests, that v2 is faster, but pypy is much faster :-)
SO: it's not good to optimize code for a single interpreter (I have not tested Jython for example...), but it's great when someone optimizes the interpreter...