AndrewMcLagan
AndrewMcLagan

Reputation: 13987

React performance: creating variables within render()

When instantiating props in the render method of a component, does that have a performance hit (albeit small)? 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}
    />
  );
}  

Upvotes: 3

Views: 522

Answers (2)

Grgur
Grgur

Reputation: 7392

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. 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

Upvotes: 5

DDS
DDS

Reputation: 4375

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. It may even be slower by 1ms over 1m iterations. But that isn't relevant or perceptible.

Upvotes: 1

Related Questions