Re:I 10x'd a TI-84 emulator's speed by replacing a switch-case
by TAForObvReasons on Monday August 08, 2022 @12:06AM
(#32382311)
You can switch on arbitrary types in JS and you can add expressions:
switch(3) {
case true: break;
case "ab" + "c": break;
case Math.random() >= 0.5 ? "heads" : new Error("tails") : break;
}
The optimizer will have to be persuaded that the switch and each case is integral before optimizing with a jump table. On the other hand, Arrays typically have a fast path for integer indices.
Re:I 10x'd a TI-84 emulator's speed by replacing a switch-case
by teruakohatu on Monday August 08, 2022 @12:55AM
(#32382485)
That explains it, but shouldn't a switch with string or numerical constants (or an expression made up of constants) just be optimized away anyway?
Re:I 10x'd a TI-84 emulator's speed by replacing a switch-case
by jcfields on Monday August 08, 2022 @01:22AM
(#32382579)
The article quotes a Stack Overflow post with the conditions under which V8 will optimize the switch statement:
> @LGB actually in V8 (JS engine used by google chrome) you need to jump through a lot of hoops to get switch case optimized: All the cases must be of same type. All the cases must either be string literals or 31-bit signed integer literals. And there must be less than 128 cases. And even after all those hoops, all you get is what you would have gotten with if-elses anyway (I.E. no jump tables or sth like that). True story.
In the case of this emulator, it wasn’t being optimized because it had more than 128 cases.
Re:I 10x'd a TI-84 emulator's speed by replacing a switch-case
by teruakohatu on Monday August 08, 2022 @01:31AM
(#32382612)
> In the case of this emulator, it wasn’t being optimized because it had more than 128 cases.
Now that makes sense. Thank you.
Re:I 10x'd a TI-84 emulator's speed by replacing a switch-case
by shultays on Monday August 08, 2022 @04:40AM
(#32383460)
But in js you can have maps of arbitrary types as keys right? So jump table could just use that
Re:I 10x'd a TI-84 emulator's speed by replacing a switch-case
by mattashii on Monday August 08, 2022 @05:01AM
(#32383559)
that's not quite true, because arbitrary expressions can change meaning due to e.g. overloading of functions.
E.g. Random.random() will have to be called each time that case branch is evaluated, because that function could be overloaded or change its returned value.
Can you explain why this is?
Intuitively it would seem like optimizing a switch statement would be really low-hanging fruit. I would have thought it would be optimized into something almost exactly like what the author hand rolled.