javascript - 有没有办法确定 if static/constant 的条件?

标签 javascript performance if-statement optimization branch-prediction

假设我有这样一个片段,

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

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

})

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

条件不依赖于数组项。

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

我能想到的几种方法是

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

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

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

    请提出更好的方法来处理这种情况,以提高效率。

最佳答案

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

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;
}

关于javascript - 有没有办法确定 if static/constant 的条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49521159/

相关文章:

javascript - 我在尝试发送嵌入时不断收到错误消息

javascript - 关于Jquery库的一些问题

performance - Grails:部署时间非常慢。 'Resolving Dependencies...' 需要 10 多秒

javascript - THREE.Camera.prototype.lookAt</<() - </< 是什么意思?

Javascript算术运算符不起作用

java - 如何使用java监控托管服务器的堆大小

php - 客户提示我的 osCommerce 网站速度慢

jquery - 单击按钮在 ionic 中使用 D3.js 显示其他图表

excel - 使用IF语句检查值

java - 仅当多个 JTextField 不为空时才保存