简体   繁体   中英

Should you define all properties of a component's state inside the constructor?

So I finished reading this article which basically talks about how v8 and other javascript engines internally cache the "shape" of objects so that when they need to repeatedly access a particular property on an object, they can just use the direct memory address instead of looking up where in that object's memory that particular property is.

That got me thinking, in React you often declare a component's state inside the constructor but don't include all the properties that will eventually be included in the state, for example:

class MyComponent extends React.Component {
   constructor(props) {
       super(props);
       this.state = {
          hasLoaded: false
       };
   }

   componentDidMount() {
       someAjaxRequest.then((response) => {
           this.setState({
              content: response.body,
              hasLoaded: true
           });
       });
   }

   render() {
       return this.state.hasLoaded ?
          <div>{this.state.content}</div> :
          <div>Loading...</div>;
   }
}

Since according to the article, the state object doesn't remain a consistent structure, would doing something like this be less efficient than defining all the possible state's fields in the constructor? Should you always at least add all the properties even giving them a value of null so that the object is always consistent? Will it impact performance in any substantial way?

TL;DR The performance wins seem to be negligible enough to not really be worth it.

Test setup:

I made 100,000 children of this class:

import React, { Component } from 'react';

const getRand = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;

class Child extends Component {
  constructor() {
    super();
    this.state = {
      loading: false,
    };
  }

  componentDidMount() {
    const key = getRand(1, this.props.numKeys);
    this.setState({
      key,
      [key]: 'bar',
    });
  }

  render() {
    if (this.props.display) {
      return <div>child {this.state.key} {this.state[this.state.key]}</div>
    }
    return <div>child 0</div>
  }
}

export default Child;

The children are made as follows:

const children = [];
for (let i = 0; i < 1 * 100 * 1000; i++) {
  children.push(<Child display={true} numKeys={1000} key={i} />);
}
return (
  <div>
    {children}
  </div>
);

The idea being: I could pass in the display prop to either render the same HTML for every child, or a different HTML.

I also passed in a numKeys to determine how many different types of keys there should be on the object. After testing, the display prop didn't significantly affect the DOM render time, so I didn't report it below. All tests were run with yarn build && serve -s build via create-react-app

Results

Same key for all children

所有孩子都有相同的钥匙

3 keys for all children

适用于所有儿童的3把钥匙

10 keys for all children

所有孩子的十把钥匙

1000 keys for all children

所有儿童均可使用1000把钥匙 *all tests in Chrome 67.0.3396.99

As you can see, the performance for 100,000 objects is negligible until you have a lot of different shaped objects. Even then, your performance increase is 700ms over 100,000 components, or 7 microseconds per component. It's certainly not the 8x speedup claimed.

MOREOVER: Your render time is likely to be dwarfed by DOM actions in anything realistic, and not synthetic like this test.

Optimizations aside, it's a good idea to model all local state fields even if it's just data: null as you mention. This way, you can reset the component back to it's initial state with a simple call to this.setState .

为了优化和提高性能,始终建议在构造函数中初始化所有组件变量,以便在组件中加载初始值,并可以在运行时避免创建新的状态变量。

the main reason to define all properties upfront is that it serves as a self documenting feature of your component.

So

  1. it reduces the need to add comments
  2. it reduces the time it takes for a developer to familiarise him/herself with the component

the long term time/maintenance gains in doing this will pay for itself, performance gains aside.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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