Using push() and withMutations()

On its own, the push() method is inexpensive in terms of CPU time or memory allocations. Where it gets expensive is when calling it over and over in a loop, as we've done in the previous example. Let's fix this so that we can use the push() method approach without having to keep allocating new collections:

wordInput.on('data', (data) => {
const words = `${last}${data.toString()}`.split(os.EOL);
last = words[words.length - 1];

myWordList = myWordList.withMutations((list) => {
for (const word of words) {
list.push(word);
}
});
});

wordInput.on('end', () => {
console.log('word count', myWordList.count().toLocaleString());
console.timeEnd('elapsed');
// -> word count 235,886
// -> elapsed: 806.099ms
});

Using the withMutations() method, we've managed to shave more time off our push() approach. This method allows us to use mutative collection methods, without having to assign new collections. As you can see, we're just calling push() without assigning the return value to anything.

Don't overuse withMutations(). Save it for the performance-sensitive areas of your code, where creating intermediary collections slows things down. Using it everywhere accomplishes nothing other than diluting the value of your functional code. Also be sure to check with the Immutable.js documentation to make sure that the method can safely be used inside withMutations(), because not every method can.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.162.26