无法为此问题找到更好的标题,因此非常感谢编辑建议。
我想知道检查条件与指定变量和内联条件之间是否存在差异 例如:
选项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是我的选择,因为它更具可读性,但我想知道是否存在行为或性能上的差异? 有没有办法测试两个选项之间的性能?
答案 0 :(得分:2)
如果您想将短路评估的好处与可读性和命名变量相结合,那么
function isSomething(){
const conditionA = () => 1 > 2 || 'a' == 'a' || 2 < 4;
const conditionB = () => 55 == 1 || (32 > 4 || 'a' == 'a') && 6 > 2;
const conditionC = () => 'abc' != 'bca' && 3 == 3;
const result = conditionA() || conditionB() || conditionC();
return result;
}
答案 1 :(得分:-1)
至于检查性能,我会看jsperf。
另请注意console.time()
,console.profile()
和performance.now()
(如果您还没有)。
在选项2中,您创建了3个新对象并将它们分配给变量,创建对象并将它们分配到内存中,这对性能的影响往往是微不足道的。
在选项1中,如果第一个值为真,则不评估第二个选项,因为||
是短路操作符,而在第二个选项中,无论返回的结果如何,都将评估所有三个条件。 / p>
如果性能是一个问题,因为多次使用此方法,我总是建议性能测试尽可能模拟真实世界的应用程序。