因为窥视孔优化器通过预先计算乘法的结果来优化它
import dis
dis.dis(compile("10 / float(98765)", "<string>", "eval"))
1 0 LOAD_CONST 0 (10)
3 LOAD_NAME 0 (float)
6 LOAD_CONST 1 (98765)
9 CALL_FUNCTION 1
12 BINARY_DIVIDE
13 RETURN_VALUE
dis.dis(compile("10 / (98765 * 1.0)", "<string>", "eval"))
1 0 LOAD_CONST 0 (10)
3 LOAD_CONST 3 (98765.0)
6 BINARY_DIVIDE
7 RETURN_VALUE
98765 * 1.0
它将字节码中的结果存储为常量值。所以,它只需要加载它并划分,在第一种情况下,我们必须调用函数。
我们可以像这样更清楚地看到
print compile("10 / (98765 * 1.0)", "<string>", "eval").co_consts
# (10, 98765, 1.0, 98765.0)
由于该值是在编译时预先计算的,因此第二个更快。
编辑:正如Davidmh 在评论中指出的那样,
它没有优化除法的原因是因为它的行为取决于标志,比如标志,from __future__ import division
也因为-Q
标志。
引用Python 2.7.9 的实际窥视孔优化器代码中的评论,
/* Cannot fold this operation statically since
the result can depend on the run-time presence
of the -Qnew flag */