简体   繁体   中英

React: Props destructuring and memory usage

Does using destructuring assignments affect memory usage/performance if the declared constants are only used once ? In other languages (Java, C, etc), it's best not to declare a variable if it's only used once, as it allocates unnecessary memory . Is this also true with ES6 JS?

I have 2 examples of what I'm talking about. The first uses destructuring assignments and calls each constant just once. The second calls this.props each time it is used and does not declare them in advance. Which one uses less memory? Our code base is pretty evenly split between the 2, but I'm curious as to which way is better for scale.

with destructuring assignment for single-reference variables:

render(){
   const {
      a, b, c, d, e, f, g, h, i
   } = this.props;
   return(
      <div>
         <div id={a}>some text relevant to a</div>
         <div id={b}>some text relevant to b</div>
         <div id={c}>some text relevant to c</div>
         <div id={d}>some text relevant to d</div>
         <div id={e}>some text relevant to e</div>
         <div id={f}>some text relevant to f</div>
         <div id={g}>some text relevant to g</div>
         <div id={h}>some text relevant to h</div>
         <div id={i}>some text relevant to i</div>
      </div>
   );
}

without declaring constants for single-reference variables:

render(){
   return(
      <div>
         <div id={this.props.a}>some text relevant to a</div>
         <div id={this.props.b}>some text relevant to b</div>
         <div id={this.props.c}>some text relevant to c</div>
         <div id={this.props.d}>some text relevant to d</div>
         <div id={this.props.e}>some text relevant to e</div>
         <div id={this.props.f}>some text relevant to f</div>
         <div id={this.props.g}>some text relevant to g</div>
         <div id={this.props.h}>some text relevant to h</div>
         <div id={this.props.i}>some text relevant to i</div>
      </div>
   );
}

There is no difference between both code in terms of performance and memory usage.

It's more about code readability : your first solution makes the JSX less verbose and easier to read. Especially if you reuse several time the same props.

When you have a doubt about performance or memory usage, open the Google Chrome Developer Tools and start monitoring your app. Don't micro-optimize before detecting a problem.

I would argue with the first answer. When doing

const {
      a, b, c, d, e, f, g, h, i
} = this.props;

you allocate memory for these variables. Although you'll need some extra memory, it wont be significant because objects (including arrays, functions etc) will be defined as references/pointers.

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