Javascript 使用键vs条件语句获取值
我试图优化滑块的性能,该滑块有许多在滑动/滑动时执行的条件语句 哪种方式性能更好 1-使用关键条件访问准备好的对象Javascript 使用键vs条件语句获取值,javascript,performance,typescript,ecmascript-6,conditional,Javascript,Performance,Typescript,Ecmascript 6,Conditional,我试图优化滑块的性能,该滑块有许多在滑动/滑动时执行的条件语句 哪种方式性能更好 1-使用关键条件访问准备好的对象 const controller = (config) => { top: { positionVertical: false, orderAfter: false, width: '100%', height: config.height + 'px', }, bottom: { posit
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',
}
}
})
);
额外的解释非常感谢这么简单,我做了个测试
很可能您永远不会看到这两个版本的代码之间有任何性能差异。根据袁的测试结果,即使滑块中有10000个条目,也不会有任何明显的差异。我假设这些测试是在桌面CPU上进行的,但即使是在移动CPU上,也不会有太大区别 这就是说,从第一个原则很容易判断哪个版本可能更快:第二个,因为它做的工作更少。Yuan的测试证明了这一点,在10000000个条目的极端情况下(尽管我还没有查看详细的测试设置) 为什么第二个更快?看第一个。对于每个条目,它执行以下操作:
config.position
选择其中一个内部对象,并丢弃其余对象config.position
选择要创建的四种对象类型中的哪一种从风格上讲,在第二个版本中,有一点我会有所改变。
默认值:
案例应为案例“底部”:
以匹配其余部分并使意图更加明确。哪种方式性能更好?-执行这两个场景,并检查执行时间-哪个更快-使用它。从另一个角度看:OP的滑块中有10000000个条目吗?可能不会。也许1000?这似乎更有可能。因此,将每个结果除以10000。对于1000个条目,第一个函数现在是.028ms,而第二个函数是.016ms。这是一个惊人的0.012毫秒的速度。现在,运行这段代码是否重要,是否要快0.012ms?那么您可能会关心这两个版本的性能。否则,性能差异无关紧要,其他因素应告知使用哪个版本。如果我们的产量不超过1000000,我们不知道哪个更快,这只是回答问题。事实上,当然,我们在一个页面中没有超过10000000个条目。这就是我的观点:在实际使用代码时,性能差异不太可能起作用。即使输入10000个条目,差异也只有十分之一毫秒。当然,你的测试仍然很有用,即使它只是证明在实践中不会有太大的差异。谢谢交流