具有分配变量的条件与内联条件检查
Conditions with assigned variables vs inline condition check
无法为该问题找到更好的标题,因此将不胜感激编辑建议。
我想知道使用赋值变量检查条件和内联条件是否有区别。
例如:
选项 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 中理论上它可以 return 在第一次检查它是否 true
之后。
显然选项 2 是我的选择,因为它更具可读性,但我想知道在行为或性能上是否存在差异?
有没有办法测试这两个选项之间的性能?
至于检查性能,我会查看 jsperf。
另外请看一下 console.time()
、console.profile()
和 performance.now()
(如果您还没有看的话)。
在选项 2 中,您正在创建 3 个新对象并将它们分配给变量,创建对象并将它们分配到内存中,这对性能的影响往往是微不足道的。
在选项 1 中,如果第一个值为真,则不会评估第二个选项,因为 ||
是短路运算符,而在第二个选项中,将评估所有三个条件,而不管它们 return.
如果性能是一个问题,因为这个方法被多次使用,我总是建议性能测试尽可能模拟真实世界的应用程序。
如果您想将短路计算的优点与可读性和命名变量结合起来,那么
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:
// 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 中理论上它可以 return 在第一次检查它是否 true
之后。
显然选项 2 是我的选择,因为它更具可读性,但我想知道在行为或性能上是否存在差异? 有没有办法测试这两个选项之间的性能?
至于检查性能,我会查看 jsperf。
另外请看一下 console.time()
、console.profile()
和 performance.now()
(如果您还没有看的话)。
在选项 2 中,您正在创建 3 个新对象并将它们分配给变量,创建对象并将它们分配到内存中,这对性能的影响往往是微不足道的。
在选项 1 中,如果第一个值为真,则不会评估第二个选项,因为 ||
是短路运算符,而在第二个选项中,将评估所有三个条件,而不管它们 return.
如果性能是一个问题,因为这个方法被多次使用,我总是建议性能测试尽可能模拟真实世界的应用程序。
如果您想将短路计算的优点与可读性和命名变量结合起来,那么
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;
}