javascript - 在 javascript : any speed advantage? 中嵌套 'switch' 个案例

标签 javascript performance switch-statement

新手问题:我有一个包含大量字符串的“开关”。像这样按字母顺序拆分是否有速度优势?

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/

相关文章:

javascript - 具有当前 View 位置的 css 动画整页

javascript - PhantomJS.Org 响应我的 phantom js 脚本花费的时间太长?

javascript - 解析 JavaScript 对象以呈现 highcharts

performance - 故障硬件 : How "smart" is it?

switch-statement - 检查 switch 语句中的数字

javascript - 从目录和子目录中获取数组中的所有图像

java - 为什么 Java Optional 性能会随着链接调用的数量而增加?

javascript - 过滤对象数组的性能

sql - 在 Sql 中,如何使用 case 语句更改值?

python-3.x - 匹配语句 "NaN"