Python中的重复算术

I_R*_*vic 4 python

从纯粹的性能角度来看,将重复算术运算的结果分配给变量并在整个代码中使用该变量通常是最佳实践吗?或者Python有一些内部方式来缓存结果并在遇到重复语句时使用它.

例如,这更有效:

a = 50
b = a*12-1
c = a*b

print c
#some code
print c*100 + 10
#some code
print c/100 + 20
#etc
Run Code Online (Sandbox Code Playgroud)

比这个:

print 50*(50*12-1)
#some code
print 50*(50*12-1) * 100 + 10
#some code
print 50*(50*12-1) / 100 + 20
#etc
Run Code Online (Sandbox Code Playgroud)

Joh*_*ooy 7

我不知道任何缓存中间结果的Python实现.绑定局部变量非常便宜,因此经过几次计算后,它会更快出来.

在仅使用常量的特殊情况下,窥视孔优化器可以将这些常量减少到常量

例如.

$ python3.3
Python 3.3.0 (default, Sep 29 2012, 17:17:45) 
[GCC 4.7.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> def x():
...     50*(50*12-1)
...     50*(50*12-1) * 100 + 10
...     50*(50*12-1) / 100 + 20
... 
>>> dis.dis(x)
  2           0 LOAD_CONST               9 (29950) 
              3 POP_TOP              

  3           4 LOAD_CONST              14 (2995010) 
              7 POP_TOP              

  4           8 LOAD_CONST              19 (319.5) 
             11 POP_TOP              
             12 LOAD_CONST               0 (None) 
             15 RETURN_VALUE         
Run Code Online (Sandbox Code Playgroud)

如有疑问,请选择可读版本.如果你真的需要那些额外的微秒,微优化