Skip to content

VM: Double switch statement speed by not emitting the ranges dispatch if there are no range cases - #1165

Open
schungx wants to merge 2 commits into
mainfrom
vm-optimize-switch
Open

schungx wants to merge 2 commits into
mainfrom
vm-optimize-switch

Conversation

@schungx

@schungx schungx commented Sep 9, 2026

Copy link
Copy Markdown
Collaborator

A very simple optimization for the switch statement.

Currently, a single switch statement lowers into two calls to Op::Switch -- one for the cases and one for the ranges.

In the predominant scenario of no range cases, there is no need to emit the dispatch to empty ranges.

This PR optimizes the lowering such that no second dispatch is emitted if there are no range cases. It also saves the push and pop of the Scope by not storing the switch value.

Speed of the switch statement doubles to close to 2x the speed of the AST walker when there are no range cases.

@schungx
schungx requested a review from ImTheSquid September 9, 2026 15:26
@schungx schungx added enhancement vm Issues related to the Rhai Grain bytecodes compiler and VM. labels Sep 9, 2026
Comment thread src/grain/compile/mod.rs Outdated
@schungx
schungx force-pushed the vm-optimize-switch branch 2 times, most recently from c407bdb to 5afa2fb Compare September 14, 2026 07:20
@schungx
schungx requested a review from ImTheSquid September 14, 2026 07:25
@schungx

schungx commented Sep 14, 2026

Copy link
Copy Markdown
Collaborator Author

@ImTheSquid I have re-architect the PR. The push to scope is removed completely. The scope is no longer touched.

Instead, the Switch op is modified so that it does not pop the value, only inspects it. This is done to allow a subsequent Switch op call to also inspect eh value.

The compiler only emits a pop at the end of the switch statement running to completion.

The only tricky aspect is that those "stack surpluses" must also be popped if there is a break statement terminating an outer loop prematurely. So I keep a count of how many of these surpluses exist.

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

Labels

enhancement vm Issues related to the Rhai Grain bytecodes compiler and VM.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants