This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Title: Unnecessary JUMP_FORWARD(0) (NOP) in if statements without else or elif
Type: performance Stage: resolved
Components: Interpreter Core Versions: Python 3.5
Status: closed Resolution: duplicate
Dependencies: Superseder: If without else generates redundant jump
View: 11471
Assigned To: Nosy List: Attila.Fazekas, jcea, serhiy.storchaka
Priority: normal Keywords: patch

Created on 2014-09-07 23:15 by Attila.Fazekas, last changed 2022-04-11 14:58 by admin. This issue is now closed.

File name Uploaded Description Edit
python_nop_ifelse.patch Attila.Fazekas, 2014-09-07 23:15 python_nop_ifelse.patch review
Messages (3)
msg226547 - (view) Author: Attila Fazekas (Attila.Fazekas) * Date: 2014-09-07 23:15
The following example function compiles to bytecode which contains,
an unnecessary JUMP_FORWARD 0 instruction:

def func():
    if a: pass

  2           0 LOAD_GLOBAL              0 (a)
              3 POP_JUMP_IF_FALSE        9
              6 JUMP_FORWARD             0 (to 9)
        >>    9 LOAD_CONST               0 (None)
             12 RETURN_VALUE  

  2           0 LOAD_GLOBAL              0 (a)
              3 POP_JUMP_IF_FALSE        6
        >>    6 LOAD_CONST               0 (None)
              9 RETURN_VALUE

The above JUMP_FORWARD instruction increases the code size and also has a negative performance effect.
I do not see any reason to have the extra NOP in the byte code in this case.


The attached patch removes this NOP generation from the code compilation part, so it will take effect by default.

I had a little trouble when the code compiled from ast,
because the If.orelse had a different content. (NULL vs. zero sizes asdl_seq)

* The generated Assembly code updated in dis unit test.
* The compilation test updated to test a real 'if' by using a variable in the condition. (The True and False is not a variable anymore)
msg226554 - (view) Author: Jesús Cea Avión (jcea) * (Python committer) Date: 2014-09-08 02:24
What about the peephole optimizer?.
msg226560 - (view) Author: Serhiy Storchaka (serhiy.storchaka) * (Python committer) Date: 2014-09-08 07:28
This is a duplicate of issue11471.

Explicit check for NULL is not needed because the asdl_seq_LEN() macro checks its argument for NULL.
Date User Action Args
2022-04-11 14:58:07adminsetgithub: 66554
2014-09-08 07:28:36serhiy.storchakasetstatus: open -> closed
versions: - Python 3.1, Python 2.7, Python 3.2, Python 3.3, Python 3.4
superseder: If without else generates redundant jump
messages: + msg226560

resolution: duplicate
stage: resolved
2014-09-08 02:24:38jceasetnosy: + jcea
messages: + msg226554
2014-09-08 00:11:12pitrousetnosy: + serhiy.storchaka
2014-09-07 23:15:51Attila.Fazekascreate