在javascript中嵌套'切换'案例:任何速度优势? [英] nesting 'switch' cases in javascript: any speed advantage?

查看:48
本文介绍了在javascript中嵌套'切换'案例:任何速度优势?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

新手问题:我有一个包含大量字符串的开关。按字母顺序分割它有速度优势吗?

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?

推荐答案

是和否。您会看到最低速度增益,但不值得从这种结构中丢失代码可读性。 switch语句就像if-else语句的巨大块。它必须从一个案例转到另一个案例,直到它找到它正在寻找的东西,就像if-elseif-else结构相当于它。因此,你所做的只是帮助它跳过一些条件。嵌套的switch语句,特别是这里编写的方式,对于大多数开发人员而言,其可读性低于直接if-elseif-else层次结构。

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.

这篇关于在javascript中嵌套'切换'案例:任何速度优势?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆