Using push()

The data event allows us to process data as it becomes available. However, concatenating the values to our list can be a real bottleneck—especially when we're working with thousands of items. Let's change our approach from using concat() to using push() to build the list, as follows:

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

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

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

You would think that concat() has an advantage over push() because it can add many values to collections without having to create several intermediary collection instances. In this example, every time we call push(), we're creating a new collection, which can get expensive. With concat(), we're only creating one new collection, but the work performed inside of concat() is clearly more expensive than creating new collections with push(). Can we do better still?

..................Content has been hidden....................

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