JS switch 语句:最有可能的情况优化重要吗?

发布于 2024-12-12 02:54:18 字数 289 浏览 0 评论 0原文

假设这个构造

switch(foo) {
    case "foo":
        // ...
    break;
    case "bar":
        // ...
    break;
    ...
    default:
        // ...
    break;
}

或类似的条件块(仅限通用逻辑运算符),从性能角度来看,实际上将最可能的条件放在第一位是否有意义?

如果是这样,那么它开始有意义的阈值是多少,而不是弄清楚最可能的情况是什么?

Assuming this construct

switch(foo) {
    case "foo":
        // ...
    break;
    case "bar":
        // ...
    break;
    ...
    default:
        // ...
    break;
}

or a similar conditional block (generic logical operators only), would it make sense, performance-wise, to actually put the most likely condition first?

And if so, what's the threshold where it begins to make sense vs. the "trouble" to figure out what the most likely condition will be?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

蒲公英的约定 2024-12-19 02:54:18

这种微观优化会带来比解决的问题更多的问题。对于 Javascript,由于 JS 引擎抽象了许多实现细节,评估此类构造相对困难。分析可能也不会很有洞察力。

JS 是一种脚本语言,而不是 C。让你的代码可读且简洁——顺便说一句,这应该始终是你的口头禅,无论你用什么语言编写。

This sort of micro-optimization will cause more problems than it will solve. With Javascript, it's relatively hard to assess such constructs due to the many implementation details that JS engines abstract. Profiling won't probably be very insightful either.

JS is a scripting language, not C. Make your code readable and concise — incidentally, this should always be your mantra, no matter what language you write in.

送舟行 2024-12-19 02:54:18

答案是肯定的,这是有道理的。如果您知道某件事的正确率要高得多,为什么不将其置于第一个条件呢?我相信即使使用脚本语言,它也是合理的编程。

然而,仅仅因为它有意义,并不意味着它是必要的。如果代码不经常运行,那么顺序的重要性就可以忽略不计。但是,具有多个条件语句的大循环中的代码可能会稍微减慢算法速度。

当您注意到滞后时,就该担心了。即便如此,重构条件顺序可能会排在我要做的事情列表的底部。

The answer is yes, it would make sense. If you knew something had a much higher percentage of being true why not put it in the first condition? I believe it's sound programming even in a scripting language.

Just because it makes sense, though, doesn't make it necessary. If it's code that isn't run frequently, it's negligible how important the order matters. However, code within a large loop with several condition statements could slow down an algorithm slightly.

The time to worry about it would be when you notice a lag. Even then, refactoring the order of conditions would probably be on the bottom of my list of things to do.

涙—继续流 2024-12-19 02:54:18

它会给你买任何东西的门槛是,当你 随机暂停几次,您会在执行该 switch 语句的过程中看到它,而不是完全其他的东西。

The threshold where it would buy you anything is if, when you randomly pause it several times, you see it in the process of executing that switch statement, as opposed to something else entirely.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文