新手问题:我有一个包含大量字符串的“开关”。像这样按字母顺序拆分是否有速度优势?
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
或者脚本语言无论如何都会读取每一行,只是为了找到右括号?
最佳答案
是也不是。您会看到最小的速度增益,但不值得因这种结构而损失的代码可读性。 switch 语句就像一大块 if-else 语句。它必须从一种情况转到另一种情况,直到找到它要查找的内容,就像使用与其等效的 if-elseif-else 结构一样。因此,您所做的只是帮助它跳过一些条件。嵌套的 switch 语句,尤其是此处的编写方式,对于大多数开发人员而言,不如直接向上的 if-elseif-else 层次结构可读。
关于javascript - 在 javascript : any speed advantage? 中嵌套 'switch' 个案例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7807970/