在 JavaScript 中使用 switch 语句而不是一堆 if()else if() 是否会带来性能提升?
只是好奇如果事情发生会运行得更快,或者在缓存中布局得更好,或者可以通过使用开关来提高性能?至少我知道它看起来不错,并且允许下一个代码看到所有接下来的顺序语句都依赖于同一变量的评估。
Possible Duplicate:
Javascript switch vs. if…else if…else
just curious if things will run faster or be laid out in cache nicer or something that might increase performance by using a switch? At very least I know it looks nice and allows the next code to see that all the next sequential statements are dependent upon the evaluation of the same variable.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一般来说,
switch
比if - else if
语句更快。但是,如果最多有 3 个条件,最佳实践是使用
if - else if
。如果您想要超越这个范围,您应该使用switch
语句。if else
的问题在于它可能需要多次检查才能最终到达要执行的代码。因此,您还需要优化条件语句的顺序。如果您期望
baz
为true
且foo
/bar
,那么从性能角度来看,该代码没有多大意义大多数时候都是false
。In general,
switch
is faster thanif - else if
statements.However, kind of best practice is to use
if - else if
if you got max 3 conditionals. If you're going beyond that, you should useswitch
statements.The problem with
if else
is that it possibly needs to check multiple times before it finally reaches the code to execute. Therefore you also need to optimize the order for your conditional statements.That code would not make much sense from a performance prospective if you expect
baz
to betrue
andfoo
/bar
to befalse
most of the times.