Skip to content

Commit 44bbb18

Browse files
[mypyc] feat: optimize away first index check in for loops if length > 1 (#19933)
It is not necessary to enter the gen_condition block on the first iteration if the length is known to be positive, we can safely skip it. This won't be particularly impactful but its a low-hanging fruit.
1 parent 8392e1a commit 44bbb18

File tree

3 files changed

+14
-1
lines changed

3 files changed

+14
-1
lines changed

mypyc/irbuild/for_helpers.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -183,7 +183,12 @@ def for_loop_helper_with_index(
183183

184184
builder.push_loop_stack(step_block, exit_block)
185185

186-
builder.goto_and_activate(condition_block)
186+
if isinstance(length, Integer) and length.value > 0:
187+
builder.goto(body_block)
188+
builder.activate_block(condition_block)
189+
else:
190+
builder.goto_and_activate(condition_block)
191+
187192
for_gen.gen_condition()
188193

189194
builder.activate_block(body_block)

mypyc/test-data/irbuild-lists.test

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -645,6 +645,7 @@ L0:
645645
r0 = 'abc'
646646
r1 = PyList_New(3)
647647
r2 = 0
648+
goto L2
648649
L1:
649650
r3 = r2 < 3 :: signed
650651
if r3 goto L2 else goto L4 :: bool
@@ -690,6 +691,7 @@ L0:
690691
r0 = 'abc'
691692
r1 = PyList_New(3)
692693
r2 = 0
694+
goto L2
693695
L1:
694696
r3 = r2 < 3 :: signed
695697
if r3 goto L2 else goto L4 :: bool
@@ -798,6 +800,7 @@ L0:
798800
r0 = b'abc'
799801
r1 = PyList_New(3)
800802
r2 = 0
803+
goto L2
801804
L1:
802805
r3 = r2 < 3 :: signed
803806
if r3 goto L2 else goto L8 :: bool
@@ -952,6 +955,7 @@ L0:
952955
r18 = CPyList_Extend(r10, r17)
953956
r19 = PyList_New(13)
954957
r20 = 0
958+
goto L2
955959
L1:
956960
r21 = var_object_size r10
957961
r22 = r20 < r21 :: signed

mypyc/test-data/irbuild-tuple.test

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -417,6 +417,7 @@ L0:
417417
r0 = 'abc'
418418
r1 = PyTuple_New(3)
419419
r2 = 0
420+
goto L2
420421
L1:
421422
r3 = r2 < 3 :: signed
422423
if r3 goto L2 else goto L4 :: bool
@@ -462,6 +463,7 @@ L0:
462463
r0 = 'abc'
463464
r1 = PyTuple_New(3)
464465
r2 = 0
466+
goto L2
465467
L1:
466468
r3 = r2 < 3 :: signed
467469
if r3 goto L2 else goto L4 :: bool
@@ -570,6 +572,7 @@ L0:
570572
r0 = b'abc'
571573
r1 = PyTuple_New(3)
572574
r2 = 0
575+
goto L2
573576
L1:
574577
r3 = r2 < 3 :: signed
575578
if r3 goto L2 else goto L8 :: bool
@@ -879,6 +882,7 @@ L0:
879882
r18 = CPyList_Extend(r10, r17)
880883
r19 = PyTuple_New(13)
881884
r20 = 0
885+
goto L2
882886
L1:
883887
r21 = var_object_size r10
884888
r22 = r20 < r21 :: signed

0 commit comments

Comments
 (0)