Skip to content

GDScript: Improve IF statement performance when using logical and/or expressions#120660

Draft
aurpine wants to merge 1 commit into
godotengine:masterfrom
aurpine:improve-if-statement-logical-binary-op
Draft

GDScript: Improve IF statement performance when using logical and/or expressions#120660
aurpine wants to merge 1 commit into
godotengine:masterfrom
aurpine:improve-if-statement-logical-binary-op

Conversation

@aurpine

@aurpine aurpine commented Jun 26, 2026

Copy link
Copy Markdown
Contributor

Summary

Improve GDScript IF statement performance when and and or operators are used. Instead of storing the result of these logical operators, we can use jumps.

TODO

  • Tests
  • Proper benchmarks
  • Logical not (possibly separate PR)

Problem

Currently the code

if a and b:
    pass

will compile to

 0: line 2:    if a and b:
 2: jump-if-not stack(3) to 12
 5: jump-if-not stack(4) to 12
 8: assign stack(5) = true
 10: jump 14
 12: assign stack(5) = false
 14: jump-if-not stack(5) to 21
 17: assign stack(5) = null
 19: line 3:           pass
 21: == END ==

Essentially, we are assigning the result of the condition expression to a variable before branching based on the variable. Though it is short-circuiting, the assignment happens regardless.

Solution

Instead of jumping to set a variable, we will directly jump to either the if branch or else branch (if applicable).

With the fix applied, the generated bytecode for the previous example is

 0: line 2:    if a and b:
 2: jump-if-not stack(3) to 10
 5: jump-if-not stack(4) to 10
 8: line 3:            pass
 10: == END ==

Result

Initial testing shows the change is 30-35% faster when a single operator is used.

Generated bytecode is reduced by up to 79%. Old code would add at least 14 addresses per additional operator, while the new code adds at least 3.

Future Work

Apply similar changes to:

  • while
  • match

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants