Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nesting 'switch' cases in javascript: any speed advantage?

newbie question here: I have a 'switch' containing numerous strings. Is there a speed advantage in splitting it alphabetically, like this?

switch(myString.substring(0,1)){
case "a" : switch(myString){
           case "a string beginning with a"       : runCode(); break;
           case "another string beginning with a" : runCode(); break;
           } break;
case "b" : switch(myString){
           case "by golly another string"         : runCode(); break;
           case "blimey - hundreds of strings"    : runCode(); break;
           //... etc

Or does a scripted language read every line anyway, just to find the closed brackets?

like image 370
Chris Tolworthy Avatar asked Dec 13 '22 08:12

Chris Tolworthy


2 Answers

Yes and no. You'd see a minimum speed gain, but not worth the code readability lost from this sort of structure. A switch statement is like a giant block of if-else statements. It has to go from one case to another until it finds what it's looking for, just like with the if-elseif-else structure equivalent to it. Thus all you're doing is to helping it skip over a handful of conditions. The nested switch statements, especially the way written here, are less readable for most developers than a straight up if-elseif-else hierarchy.

like image 88
Mike Thomsen Avatar answered Dec 31 '22 13:12

Mike Thomsen


I don't think you should mind such optimization. I would say it's better to create an object with the functions to be executed, so that you don't need exessive lookup code, but just something like this:

var obj = {
    "aa": runCode,
    "ab": something,
    "ba": foo,
    "bb": bar
};

Then you can execute with only this, instead of switches inside switches. It will look up the correct function internally, which I really think is faster than doing such things yourself:

obj[myString]();
like image 36
pimvdb Avatar answered Dec 31 '22 13:12

pimvdb