Python中的翻译器优化 [英] Interpreter optimization in Python
问题描述
说我在x
中有一个字符串,Python解释器足够聪明地知道:string.replace(x, x)
应该转换为NOP
吗?
Say I have a string in x
, is the Python interpreter smart enough to know that: string.replace(x, x)
should be converted to a NOP
?
如何找到这个?是否有任何参考资料显示解释器能够基于句法分析动态地执行哪种类型的优化?
How can I find this out? Are there any references that show what type of optimizations the interpreter is able to do dynamically based on syntactic analysis?
推荐答案
否,Python无法对NOP做出假设;它无法在编译时知道对象string
是什么类型,也无法在程序运行期间始终保持该类型.
No, Python cannot make assumptions about NOPs; it cannot know at compile time what type of object string
is, nor that it'll remain that type throughout the run of the program.
有 在编译时进行了一些优化,主要是在窥孔优化器.这样的事情:
There are some optimisations applied at compile time, mostly in the peephole optimiser. This does things like:
-
用不变的等价替换成员资格测试中使用的
list
和set
文字;这仅在未分配文字对象的情况下才有效,仅在比较中使用;例如:
Replace
list
andset
literals used in a membership test with immutable equivalents; this only works if the literal object is not assigned, only used in a comparison; e.g.:
if foo in ['spam', 'ham', 'eggs']:
被替换为
if foo in ('spam', 'ham', 'eggs'):
将简单的计算结果替换为:
Replace simple calculations with the result:
one_week = 7 * 24 * 60 * 60
被替换为
one_week = 604800
这也发生在序列中;如果结果序列不超过21个元素,'neener' * 3
将被该乘法结果替换.
This happens for sequences too; 'neener' * 3
is replaced with the result of that multiplication, provided the resulting sequence stays under 21 elements.
这些优化仅是可能的,因为它涉及不可变的文字值.完全受解释器控制的常量值,可以依靠它们在执行过程中不切换类型.
These optimisations are only possible because it concerns immutable literal values; constant values that are fully under control of the interpreter and can be relied upon to not switch types halfway through execution.
这篇关于Python中的翻译器优化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!