As the title says. It's not a heavy process to begin with, so I don't think it's going to happen to a slow program when I know this, but it was surprising, so as a small story.
code
from __future__ import print_function
import timeit
print("i+=1\t", timeit.timeit("while i<1000000: i+=1", setup="i=0"))
print("i=i+1\t", timeit.timeit("while i<1000000: i=i+1", setup="i=0"))
print("a[0]+=1\t", timeit.timeit("while a[0]<1000000: a[0]+=1", setup="a=[0]"))
print("a[0]=a[0]+1\t", timeit.timeit("while a[0]<1000000: a[0]=a[0]+1", setup="a=[0]"))
text:Python2.7.8 Execution result
i+=1 0.0610518455505
i=i+1 0.0599188804626
a[0]+=1 0.108623981476
a[0]=a[0]+1 0.108937978745
text:Python3.4.1 Execution result
i+=1 0.08549419100017985
i=i+1 0.07950809699832462
a[0]+=1 0.14678418899711687
a[0]=a[0]+1 0.1382706459990004
Python3 is slower. I did not know.
Anyway. It turns out that ʻi = i + 1 is faster than ʻi + = 1
, albeit very slightly.
I haven't investigated it in detail, but the cause is probably this.
When you add assignments in the form ʻi + = 1, the Python interpreter first tries to find ʻi .__ iadd__
. And if it doesn't exist, look for ʻi .__ add__. For additions of the form ʻi = i + 1
, the Python interpreter looks for ʻi .__ add__ from the beginning. So, neither Python2 nor Python3 has ʻint .__ iadd__
.
Therefore, the processing of ʻi + = 1 is wasteful because it fails by searching for ʻint.__ iadd__
.
Therefore, the ʻi = i + 1` format is probably faster.
However, I thought that ʻa [0] + = 1 would be faster than ʻa [0] = a [0] + 1
, which requires two array references.
If you think about it carefully, it seems faster to refer to the 0th of the array more than to search for a method.
Recommended Posts