lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

On Jun 12, 2014, at 11:14 AM, Coda Highland <> wrote:

> On Thu, Jun 12, 2014 at 11:10 AM, Tim Hill <> wrote:
>> For the second case, you place each “case” in its own function, and then put these functions into a table indexed by the “switch” expression. Voila! Constant time switch, with no new syntax needed.
> Constant time with a painful amount of overhead, thus prompting the
> requests for a "proper" switch statement. :P
> /s/ Adam

If by painful overhead you mean all the typing, I’m not sure there is that much difference .. a few “function() .. end” brackets around code instead of “case …” statements.

If you mean the run-time overhead of setting up the table, this depends entirely on how often the table is used. If its only used once then yes, the overhead is probably greater than the constant time function lookup and call. But jump table style switch statements and lookup tables are inherently a performance optimization that is only really of benefit if the switch/table is used multiple times (e.g. in a loop), so in that more typical case the setup time for the table is easily amortized over the multiple invocations.

And a switch style jump table isn’t free either; it still has to be compiled. The compiler logic to inspect all the switch cases and optimize them as a jump table is non-trivial, thus making compiles slower and the compiler bigger. Given that many Lua apps are compiled once and then run once, all you are doing is moving “painful overhead” from run-time to compile-time.

Further, compilers can generally only create jump tables for switch statements when the domain is very restricted. Say, for constant integer cases over a limited range that is densely populated. Whereas using a Lua table works for any domain and range of values.