【发布时间】:2017-09-24 19:33:51
【问题描述】:
找不到更好的标题,因此非常感谢编辑建议。
我想知道使用分配变量检查条件和内联条件之间是否有区别。
例如:
选项 1:
// inline conditions check
function isSomething(){
return (1 > 2 || 'a' == 'a' || 2 < 4) ||
(55 == 1 || (32 > 4 || 'a' == 'a') && 6 > 2) ||
('abc' != 'bca' && 3 == 3);
}
选项 2:
// pre assigned variables condition check
function isSomething(){
const conditionA = 1 > 2 || 'a' == 'a' || 2 < 4; // some complex condition
const conditionB = 55 == 1 || (32 > 4 || 'a' == 'a') && 6 > 2; // some complex condition
const conditionC = 'abc' != 'bca' && 3 == 3 // some complex condition
const result = conditionA || conditionB || conditionC;
return result;
}
似乎在选项 2 中它必须检查所有 3 个条件,但在选项 1 中理论上它可以在第一次检查它是否为 true 后返回。
显然选项 2 是我的选择,因为它更具可读性,但我想知道在行为或性能方面是否存在差异? 有没有办法测试这两个选项之间的性能?
【问题讨论】:
-
至于性能测试,如果您还没有听说过 jsPerf,这可能是访问该站点的最佳时机。它有多种替代方案,所有这些都在您的浏览器中在线(例如jsben.ch/#/7XyeB)。
-
@WiktorZychla 很有趣,谢谢我不知道。虽然我有时会得到不同的结果。例如:代码块 1 最快然后代码块 2 最快
标签: javascript variables conditional-statements variable-assignment