PlutoLang / Pluto

A superset of Lua 5.4 with a focus on general-purpose programming.
https://pluto-lang.org/docs/Introduction
MIT License
337 stars 20 forks source link

Switch optimisation #860

Closed XmiliaH closed 1 month ago

XmiliaH commented 1 month ago

I would like to add an optimisation to the switch statement that makes the test for the constant cases O(log n) instead of the current O(n).

This would include adding a new upvalue (switch-caches) (name up for debate but should be not accessible from the script) to the chunk. When a switch is executed for the first time a lookup table is generated and cached under some key in this upvalue table. This lookup table maps values to case-ids and allows to generate a binary search to jump to the cases. In case no constant case matched all the dynamic cases are tested.

Would this be something that is of interest?

Sainan commented 1 month ago

Absolutely. I think my comments in #858 explain pretty well that I am very much in favour of switch blocks being optimised as long as it's Lua bytecode compatible.