Python and the need for speed

MRAB python at
Thu Apr 13 13:50:12 EDT 2017

On 2017-04-13 09:08, Steven D'Aprano wrote:
> On Wed, 12 Apr 2017 16:30:38 -0700, bart4858 wrote:
>> (Although I think Python would have difficulty in turning x+=1 into a
>> single opcode, if using normal object references and a shared object
>> model.)
> You know, since Python actually exists and isn't just a hypothetical
> language, we can find out what it actually does, not just guess :-)
>>>> import dis
>>>> code = compile("x += 1", "", "single")
>>>> dis.dis(code)
>    1           0 LOAD_NAME                0 (x)
>                3 LOAD_CONST               0 (1)
>                6 INPLACE_ADD
>                7 STORE_NAME               0 (x)
>               10 LOAD_CONST               1 (None)
>               13 RETURN_VALUE
> There's an op-code for looking up the name 'x', another to push the
> constant 1 on the stack, an op-code for "INPLACE_ADD", followed by an op-
> code for STORE_NAME again.
> In principle, we could replace the LOAD_CONST and INPLACE_ADD with a
> single op-code that combines the two. Whether that would speed anything
> up is another question.
> Is it possible to skip the STORE_NAME op-code? If you knew *for sure*
> that the target (x) was a mutable object which implemented += using an in-
> place mutation, then you could, but the only built-in where that applies
> is list so even if you could guarantee x was a list, it hardly seems
> worth the bother.
If the reference to be stored by STORE_NAME is the same as the reference 
returned by LOAD_NAME, then STORE_NAME could be omitted.

That would just mean remembering that address.

I'm still trying to think whether it's ever possible to lose all 
references to the object when INPLACE_ADD is called, leading to the 
object having been garbage-collected by the time it returns.

More information about the Python-list mailing list