Arrow functions inside map in render. React

故事扮演 提交于 2019-12-12 04:38:52

问题


I'd like to know if there is any performance difference between passing an arrow function to a map function inside render, and passing a reference to that arrow function, like so:

render {
   const { users } = this.props;

   //Arrow function passed to map,  in render. 
   const userList= 
    users.map((user) =>
     <User
      name={ user.name }
     />);

    return(
     <div>
      {userList}
     </div>
    );
 }

vs

makeUser = (user) => <User name={ this.props.user.name } />

render {
   const { users } = this.props;

   //Passing the arrow function reference
   const userList = users.map(this.makeUser);

    return(
     <div>
      {userList}
     </div>
    );
 }

Isn't the first one creating and allocating space in memory, for the arrow function, each time render is called?

Thanks


回答1:


Decoupling the function from the render method is pragmatically better and makes for a better functional approach. Although you are entirely correct in your way of thinking about the consumed resources of the initial approach there are different sides to this. The initial approach gets created at runtime, stored and mapped as a N of reference in the runtime compiler, optimized. Dare i assume V8. This happens because of the named function expression as opposed to an anonymous. I would advise you to keep the code functional, avoiding any creation of functions inside of render if possible, keep the abstraction at its most natural place.



来源:https://stackoverflow.com/questions/45002265/arrow-functions-inside-map-in-render-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!