使用键vs条件语句获取值

问题描述 投票:1回答:2

我试图优化滑块的性能,该滑块具有许多在滑动/滑动时执行的条件语句。

哪种方式有更好的表现?

1-使用键条件访问准备好的对象

const controller = (config) => {
    top: {
      positionVertical: false,
      orderAfter: false,
      width: '100%',
      height: config.height + 'px',
    },
    bottom: {
      positionVertical: false,
      orderAfter: true,
      width: '100%',
      height: config.height + 'px',
    },
    left: {
      positionVertical: true,
      orderAfter: false,
      width: config.width + 'px',
      height: '100%'
    },
    right: {
      positionVertical: true,
      orderAfter: true,
      width: config.width + 'px',
      height: '100%'
    }
};

this.gallery.sub$.pipe(
  map(({state, config}) => this.controller(config)[config.position])
);

2-使用标准的if-else或switch case语句

this.gallery.sub$.pipe(
  map(({state, config}) => {
    switch(config.position) {
       case 'top': return {
         positionVertical: false,
         orderAfter: false,
         width: '100%',
         height: config.height + 'px',
       }
       case 'left': return {
         positionVertical: true,
         orderAfter: false,
         width: config.width + 'px',
         height: '100%'
       }
       case 'right': return {
         positionVertical: true,
         orderAfter: true,
         width: config.width + 'px',
         height: '100%'
       }
       default: return {
         positionVertical: false,
         orderAfter: true,
         width: '100%',
         height: config.height + 'px',
      }
    }
  })
);

额外的解释表示赞赏

javascript performance typescript ecmascript-6 conditional
2个回答
1
投票

您很可能永远不会看到两个版本的代码之间的任何性能差异。根据Yuan的测试结果,即使您的滑块中有10,000个条目,也不会有任何明显的差异。我假设这些测试是在桌面CPU上进行的,但即使在移动CPU上,也不应该有太大的区别。

也就是说,从第一原则可以很容易地看出哪个版本可能更快:第二个版本,仅仅因为它的工作量少了很多。袁的测试证明了10,000,000个条目的极端情况(尽管我没有看过详细的测试设置)。

为什么第二个更快?看看第一个。对于每个条目,它执行以下操作:

  1. 计算所有四种情况的所有值,并为每种情况创建一个对象。
  2. 构造一个包含所有这四个内部对象的新外部对象。
  3. 根据config.position选择其中一个内部对象并丢弃其余内容。

第二个版本只是这样做:

  1. 使用config.position选择要创建的四种对象中的哪一种。
  2. 只构造一个对象而不构造其他三个对象。
  3. 没有第3步。

按理说,计算和构造四个不同的对象,加上一个包装对象来保存所有对象,所需的时间比仅计算和构造其中一个对象要长。

在风格上,我会在第二个版本中改变一件事。 default:案件应该是case 'bottom':以匹配其余的并使意图更清楚。


© www.soinside.com 2019 - 2024. All rights reserved.