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?
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.
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 switch
es inside switch
es. It will look up the correct function internally, which I really think is faster than doing such things yourself:
obj[myString]();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With