问题
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