質問

Is it faster if I filter my data before calling setProps (or setState) for Reactjs?

var component = React.renderComponent(
  <MainApp />,
  document.getElementById("container")
);

var data = {
  name: "p",
  list: [
    {id:1, name:""},
    {id:2, name:""},
    {id:3, name:""},
    //...
  ]
}
component.setProps(data);
data.name = "w";

Now I want to update the "p" to the "w". Is it more efficient/faster if I do this:

component.setProps(data);

Or this:

component.setProps({name: "w"});

The latter one doesn't need me to put the whole data object in it again, but then I have to do my own filtering.

If I put in the whole object again with only 1 thing changed, does Reactjs need to process the whole object in setProps/setState which slows it down, or will it need to process everything anyway inside render so it makes no difference?


Edit 1 hour later:

I didn't get a satisfactorily technical answer on which is faster.

Rather than get to the bottom of it, I just did a quick jsPerf testcase to see which is faster and simply accept it as a statistical truth rather than a technological truth.

http://jsperf.com/reactjs-setprops-big-or-setprops-small

The surprising thing is that giving it a large object is faster by a negligible amount. (I thought it would be slower.) I suppose internally ReactJS has to process the whole object anyways regardless of whether my input was small or big. It isn't able to skip over processing the large object (that wasn't modified), so there is no time savings in not passing it the large object.

役に立ちましたか?

解決

Passing only the key you need to update is faster by a microscopic amount, but you should pass in whatever's most convenient -- doing your own filtering will cancel out any time advantage that you might gain from passing fewer keys.

Like I said in my other answer, these small changes won't make a large enough difference to worry about. Do whatever's easiest, then only if your app is slow, look at adding shouldComponentUpdate methods to reduce unnecessary updates.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top