受this啓發關於Python緩存小整數的問題。Python編譯器是否可以優化掉某些整數算術?
編譯時Python編譯器是否可以用-6替換(0-6)?下面的代碼表明它沒有。如果不可能,爲什麼不呢?我不認爲0
,-
或6
的含義在運行時可能會有所不同。
如果這是可能的,爲什麼CPython不這樣做?萬一
# test_integers.py
def test_integers():
print "-6 is -6 ?", -6 is -6 # True
print "(0 - 6) is -6 ?", (0 - 6) is -6 # False
# import_test_integers.py
import test_integers
test_integers.test_integers()
我的Python的細節,這是非常依賴於實現:
Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56)
[GCC 4.4.3] on linux2
FWIW:這種優化稱爲「恆定摺疊」。 (我不知道CPython是否會這樣做。) – 2012-07-14 17:34:51