这里有新手问题:我有一个包含大量字符串的“开关”。像这样按字母顺序拆分是否有速度优势?
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 层次结构。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)