Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Immutable.js alternative to boost React performance

Immutable.js besides it's immutable also provide deep data structure comparison. It allow to boost React rendering performance since allow easily implement shouldComponentUpdate method or use react-immutable-render-mixin.

But, I only need deep comparison. Is there any solutions for deep data structure comparison without Immutable.js?


Update: I've got deep data tree with embedded objects/arrays. Each array entity in turn may contain another objects/arrays and so on and so forth. @MatthewHerbst I took a look at the link you post. That looks for me as a set of vehicles without tests. Also I'm not sure if that solutions can compare to pretty deep data trees, with embedded arrays inside arrays etc.

like image 823
VB_ Avatar asked May 10 '26 20:05

VB_


1 Answers

Writing your own deep-comparator is a trivial thing. Even, if you're not much into the recursion, you can just do it 'lazy way' by reusing immutableJS library (I assume, you don't mind using immutable.js on just one place) (es6 syntax used):

const deepEquals = (a, b) => immutable.is(immutable.fromJS(a), immutable.fromJS(b))

However, this solution is not very efficient for obvious reasons. If performance is your concern (but still, you dislike immutable.js for some reason), you may use the following approach:

  1. Write custom recursive deepEquals. Use the following trick: if a===b, then a and b deepEquals (no more checks are necessary, you can immediately return true. If a!==b, you must do a proper recursive for-each-key check though)

  2. In your code, avoid mutating things as much as possible (such that the trick from above will take effect as often as possible). This means,

instead of:

myObj[newkey] = newval

use:

let modifiedA = {...myObj, newkey: newval}

This way, creating modified versions of maps (and arrays) takes little more time, but the comparison can be MUCH faster (especially, if your data structure is quite nested, but your individual maps / arrays do not have many direct keys)

like image 156
Tomas Kulich Avatar answered May 13 '26 10:05

Tomas Kulich



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!