三元语句比javascript中的if / then / else语句更快吗? [英] Are ternary statements faster than if/then/else statements in javascript?
问题描述
我看到了很多:
var something = (is_something_true()) ? 3 : 4;
。这比
var something;
if (is_something_true()) {
something = 3;
} else {
something = 4;
}
还是为方便起见而写得简洁?
Or is it written concisely for convenience?
推荐答案
请享受这一点 - 如果差异在统计上有效,那么结果(真或假)也很重要 - 显然这只是机器上的其他东西对浏览器性能的影响:
Please enjoy this -- if difference is statistically valid then the result (true or false) also matters -- clearly this is just other stuff on the machine having an impact on browser performance:
两者之间存在根本区别,三元语句是表达式而不是控制流。如果有人将其写为三元表达式而不是标准if / than / else,当两者都工作相同时,他们(在我看来)会使代码更难以无理由地阅读。
There is a fundamental difference between the two, the ternary statements are expressions and not flow of control. If there is a case where someone writes it as a ternary expression instead of a standard if / than / else, when both would work the same they are (in my opinion) making the code harder to read without good reason.
就速度而言,应该没有区别。除非你使用一个非常糟糕的JavaScript实现。两个语句中最慢的部分是分支。
In terms of speed there should be no difference. Unless you are using a really bad javascript implementation. The slowest part of both statements is the branching.
这篇关于三元语句比javascript中的if / then / else语句更快吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!