Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimize ternary transpilation for assignments #1341

Merged
merged 4 commits into from
Nov 1, 2024

Conversation

TwitchBronBron
Copy link
Member

@TwitchBronBron TwitchBronBron commented Oct 31, 2024

Whenever a ternary expression is on the right-hand-side of an assignment, dottedSet, or indexedSet statement, we can transpile the entire thing to an if statement instead which improves performance significantly (should be identical to handwritten non-ternary code).

This PR adds this if statement transpiling for all of the following situations:

  • assignments: a = true ? 1 : 2
  • dotted set: m.a = true ? 1 : 2
  • indexed set: m["a"] = true ? 1 : 2
  • complex assignment operators (i.e. +=, -=, etc...) size += true ? 1 : 2
  • grouped ternaries: a = (((true ? 1 : 2)))
  • nested ternaries a = true ? (false ? 1 : 2) : 3

These are explicit cases, so any situation other than these will be transpiled according to the existing rules (basic and scope safe)

Simple example:

a = true ? 1 : 2

becomes this:

if true then
    a = 1
else
    a = 2
end if

Nested example:

result = true ? (false ? "one" : "two") : "three"

becomes this:

if true then
    if false then
        result = "one"
    else
        result = "two"
    end if
else
    result = "three"
end if

This benchmark shows a significant improvement in performace

image

Copy link

@jtuckerfubo jtuckerfubo left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm

@TwitchBronBron TwitchBronBron merged commit d2d08a7 into master Nov 1, 2024
6 checks passed
@TwitchBronBron TwitchBronBron deleted the ternary-to-if-statement branch November 1, 2024 18:22
@TwitchBronBron TwitchBronBron added the create-package create a temporary npm package on every commit label Nov 21, 2024
@rokucommunity-bot
Copy link

Hey there! I just built a new temporary npm package based on 7fee5a1. You can download it here or install it by running the following command:

npm install https://github.com/rokucommunity/brighterscript/releases/download/v0.0.0-packages/brighterscript-0.67.8-ternary-to-if-statement.20241121134906.tgz

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
create-package create a temporary npm package on every commit
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants