Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use big switch statements in JavaScript without performance problems?

I've google'd a bit but I still feel to be lost. I am writing a CPU emulator in JavaScript (namely Z80 in me case, currently). There is a huge switch statement in its heart. Though I can run some benchmarks of course, I can't be sure about future JavaScript engines of different browsers (ok, nobody can be, I know, but somebody should have greater knowledge of javascript engines of different browsers here than me ...).

Is it faster to use other constructs than switch statement? Like an array of functions, etc. Also similar problem: I have the situation to have possible prefixed Z80 opcodes. Some 'case' branches of the switch needs another switch inside, but not all. I am thinking to convert the whole stuff into an even bigger (but only one level "deep") switch construct to have opcodes between 0-255 as normal, 256-511 as 0xDD prefixed etc, some of them would have more 'case's (without break) for the single same code. Or should I avoid big switch statements as much as possible even for the base opcode table (256 'case' branches)?

For C code, compiler would create a jump table in this situation which is quite fast. But what's about javascript?

Another similar question: is it worth to have a switch statement with only two 'case' branches and a 'default' entry, or it's really the situation where if ... else is better?

It can be important to declare that I use only numeric (and integer - though it does not mean too much in JavaScript since AFAIK it only has one numeric type) values in my switch constructs.

like image 768
LGB Avatar asked Feb 15 '23 06:02

LGB


2 Answers

The switch is at least as fast as having to evaluate many ifs and elses. Even without knowing the insides of JavaScript engines and optimizers, this we know for sure.

In case of an interpreter such as your case, it might be even better to store functions in a dictionary (array) instead, and do a binary lookup of your code in that array.

So create an array with the code you would put in the cases as index and JavaScript code (functions) as values, and just execute the code you find at the array.

like image 183
Roy Dictus Avatar answered Feb 17 '23 20:02

Roy Dictus


switch is clearly going to be faster than if-else, since it runs in constant time, only requiring a single lookup. The ambiguous case might be for lookup tables.

I've modified an existing test-case for jsperf for you to compare:

http://jsperf.com/if-switch-lookup-table/18

The lookup table implementation is the fastest of the three.

like image 25
simonzack Avatar answered Feb 17 '23 20:02

simonzack