简体   繁体   English

反应性能:在render()中创建变量

[英]React performance: creating variables within render()

When instantiating props in the render method of a component, does that have a performance hit (albeit small)? 在组件的render方法中实例化props时,是否会有性能损失(尽管很小)? My theory is that on every render this variable is re-created in memory. 我的理论是,在每个渲染中,这个变量在内存中重新创建。 Over many components this could add to significant performance implications? 在许多组件中,这可能会增加显着的性能影响?

render() {

  const { title, pages, pictures, cover } = this.props;

  return (
    <Book
      title={title}
      pages={pages}
      pictures={pictures}
      cover={cover}
    />
  );
}

// VS the follow

render() {

  return (
    <Book
      title={this.props.title}
      pages={this.props.pages}
      pictures={this.props.pictures}
      cover={this.props.cover}
    />
  );
}  

Its not really adding much to memory. 它并没有真正增加内存。 You are creating a new reference that simply points to the same memory block, which is rather effective. 您正在创建一个新的引用 ,它只指向相同的内存块,这是非常有效的。

If you change the value of the reference, then you actually create a new block in memory and your reference will point to that new block. 如果更改引用的值,则实际在内存中创建一个新块,并且引用将指向该新块。 Now we have to think about conserving memory. 现在我们必须考虑保存记忆。

There are other implications: 还有其他含义:

  • how well your code minifies and 你的代码如何缩小
  • the fact that JS will have to change scope repeatedly from this to props several times in a row. 事实上,JS将不得不从反复更改范围thisprops连续数次。 If this was a larger loop or a component that updates frequently, I would definitely try to use references so that change of scope impacts cycles a bit less. 如果这是一个更大的循环或经常更新的组件,我肯定会尝试使用引用,以便范围的更改影响周期少一点。

I highly suggest this very informative video on JavaScript Classes and Scoping where Jay Garcia explains how references work in JavaScript at the 4:03 mark 我强烈建议这个关于JavaScript类和范围的非常丰富的视频,其中Jay Garcia解释了引用在4:03标记的JavaScript中如何工作

No. Also it really isn't relevant. 不,它真的没有关系。 Maybe it could be called premature optimization. 也许它可以被称为过早优化。 But it's not really optimizing anything. 但它并没有真正优化任何东西。 You should jsperf it and find that it totally does not matter at all. 你应该jsperf它,并发现它完全无关紧要。 It may even be slower by 1ms over 1m iterations. 它甚至可能比1m迭代慢1ms。 But that isn't relevant or perceptible. 但这不相关或不可察觉。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM