【问题标题】:Is there a way to make condition of if static/constant?有没有办法确定是否为静态/恒定?
【发布时间】:2018-09-06 08:25:19
【问题描述】:

假设我有一个这样的sn-p,

let arr = [{...},{...} ...]// huge array of objects;

arr.forEach(i => {
  if(someOtherProperty == "one") {
    ...
  } else if(someOtherProperty == "two") {
    ...
  }...

})

基本上,我在循环中有一个 if-else-if 阶梯。

条件不依赖于数组项。

我想知道是否可以在执行循环之前评估 if 条件,因为条件在整个循环运行期间是静态/恒定的

我能想到的几种方法是

  1. 将循环保留在每个 if/else 块内。这样 if 条件只会执行一次,但我有更多代码。
  2. 使用类似的对象

    let condition = {
      one: someOtherProperty == "one",
      two: someOtherProperty == "two",
      ...
    }
    

    并在if(condition.one)等条件中使用。

    请提出更好的处理此类情况的方法以提高效率。

【问题讨论】:

  • 你能解释一下你想要达到的目标吗?
  • @Phiter,感觉代码效率低下。由于数组的大小很大,并且有很多 else-if 块。对于每次迭代,都会评估条件,我认为可以在循环运行之前完成但不知道最好的方法。
  • switch 声明在这里有用吗?我不太确定我是否理解这个问题。
  • @jhpratt 看到我上面的评论,我想我已经说得更清楚了。
  • 如果预期结果一致,branch prediction 可能会或可能不会影响 if 语句的速度,因此可能根本不需要预优化。由于上下文切换开销,您最大的减速将是使用 forEach() 而不是 for 语句。

标签: javascript performance if-statement optimization branch-prediction


【解决方案1】:

我认为在这种情况下,条件句中的代码之间存在巨大差异,您可以使用以下方法使您的代码看起来更好:

let arr = [1, 2, 3, 4, 5];
let str = "one";
const conditions = {
  "one": function(item, index) {
    console.log("one", item);
  },
  "two": function(item, index) {
    console.log("two", item);
  }
}

arr.forEach(conditions[str]);

或者如果你想坚持基础,你也可以这样做:

let arr = [1, 2, 3, 4, 5];
let str = "one";
var one = function(item, index) {
  console.log("one", item);
};
var two = function(item, index) {
  console.log("two", item);
};
switch (str) {
  case "one":
    arr.forEach(one);
    break;
  case "two":
    arr.forEach(two);
    break;
}

【讨论】:

    【解决方案2】:

    为了节省代码重复,您可以执行一次条件检查,遍历循环,然后将其余代码放入函数中。

    您还可以将循环迭代代码放在一个函数中并调用它,具体取决于您在循环中执行的操作。

    let arr = [{...},{...} ...]// huge array of objects;
    
    if(someOtherProperty == "one") {
        arr.forEach(i => { ...functionOnArray(); });
        functionOne();
    } else if(someOtherProperty == "two") {
        arr.forEach(i => { ...functionOnArray(); });
        functionTwo();
    }...
    
    function functionOnArray(){ ... }
    function functionOne(){ ... }
    function functionTwo(){ ... }
    

    【讨论】:

      【解决方案3】:

      想到的最佳解决方案是为此使用函数式方法。

      let arr = [1,2,3,4,5,6,7,8,9]; // Huge array
      
      let condFactory = (condition) => {
          if (condition === 'one') {
              console.log('This will only be called once, if condition==="one"',
                          'it will not be called for each element')
              return (item, index) => console.log('one (called for each element)', item, index);
          } else if (condition === 'two') {
              console.log('This will only be called once, if condition==="two"',
                          'it will not be called for each element')
              return (item, index) => console.log('two (called for each element)', item, index);
          }
      
          console.log('This will only be called once, if no condition matches',
                      'it will not be called for each element')
          return (item, index) => console.log('No condition matched (called for each element)', item, index);
      }
      
      arr.forEach(condFactory(someOtherProperty));
      

      对于 es5:

      var arr = [1,2,3,4,5,6,7,8,9]; // Huge array
      
      var condFactory = function(condition) {
          if (condition === 'one') {
              console.log('This will only be called once, if condition==="one"',
                          'it will not be called for each element')
              return function(item, index) { console.log('one (called for each element)', item, index); };
          } else if (condition === 'two') {
              console.log('This will only be called once, if condition==="two"',
                          'it will not be called for each element')
              return function(item, index) { console.log('two (called for each element)', item, index); };
          }
      
          console.log('This will only be called once, if no condition matches',
                      'it will not be called for each element')
          return function(item, index) { console.log('No condition matched', item, index); };
      }
      
      arr.forEach(condFactory(someOtherProperty));
      

      这样,用于每个条件的函数将在循环开始之前确定并用于循环内的每个元素。

      你可以拉伸这个oneliner

      arr.forEach(condFactory(someOtherProperty));
      

      分成两行,看看为什么 if...else 只计算一次:

      let functionBasedOnIfElse = condFactory(someOtherProperty); // Get the function based on your "someOtherProperty"
      arr.forEach(functionBaseOnIfElse); // Pass reference to the function
      

      如您所见,if...else 只会被评估一次。 if...else 返回的函数将被传递给 arr.forEach 并为数组中的每个元素调用。

      编辑:添加默认返回。

      Edit2:更正 es5 被剪断

      Edit3:扩展案例以显示每个函数都应用于数组中的每个项目。

      Edit4:添加更多关于为什么 if...else 只被评估一次的信息。

      Edit5:添加几个console.log 以显示哪个部分将在哪个点被调用。

      【讨论】:

      • 您的 sn-p/方法与所提供的方法有何不同?
      • condFactory(someOtherProperty) 根据条件返回一个函数。扩展示例:let determinedFunction = condFactory(someOtherProperty); // The function based on the conditionarr.forEach(determinedFunction) // pass the function reference 这样,if...else 将仅确定一次 -> 基于返回的函数 -> 将为数组中的每个元素调用此函数。我将更新答案以包含此内容。
      • @SatishKumar 我更新了我的答案以显示它与问题中的方法有何不同。
      • 我相信您对“这样,if...else 将只确定一次”部分是错误的。您刚刚传递了函数,它将为数组中的每个元素调用。因此,每次都会评估条件。还有问题中的 sn-p 和你的等价物。您所做的只是将循环体放入函数中。
      • 这不是真的。 condFactory() 函数只被调用一次。然后它根据条件仅返回一次 来返回函数。该函数确实会为每个元素调用一次,但它只包含您要为该条件运行的代码,而不是条件本身。我将再次更新答案以明确这一点。
      【解决方案4】:

      您可以做的一件事是创建一个映射到数组的分支非匿名函数。例如。

      f =  {(x => if (prop1 == "one") 
           { ...} 
           else if (prop2 == "two") 
           {...} )}
      

      然后执行arr.forEach(i=> f(i))。这正是实现 javascript 的功能特性的目的。

      这与您尝试执行的操作大致一样有效。如果您尝试巧妙地处理partial application 并将条件作为参数传递给该函数,它会变得更快。

      【讨论】:

      • 这种语法甚至无效。
      • 相当于题中的sn-p。
      • x => if (...)不等同于x => { if (...) }。前者是语法错误。无括号箭头函数中不能存在非表达式语句。
      猜你喜欢
      • 1970-01-01
      • 2010-09-12
      • 2011-08-26
      • 1970-01-01
      • 1970-01-01
      • 2011-01-25
      • 1970-01-01
      • 1970-01-01
      • 2010-11-30
      相关资源
      最近更新 更多