Use JavaScript Generator Functions to Reduce Memory Utilization

August 19, 2019 0 Comments

Use JavaScript Generator Functions to Reduce Memory Utilization



Now I want to show you a comparison of a generator function and an ordinary function in a for loop statement on a large number of items.

Let’s assume we need to iterate over a large amount of random numbers and do something with each one. In a normal JavaScript function, it would take the form as shown below:

Function that generates amount of random numbers and returns them

To do the same thing with a JavaScript generator function, we would use the following code:

JS Generator function for creating amount of random numbers

To test both functions I will create a main() function that will check how the memory usage changed after each iteration over the items.

The main function that uses provided <code class="ly ni nj nk b">functionToExec</code> in for loop to iterate the random items and shows memory used difference before and after the function call

I calculated the memory usage with a simple function that utilizes the performance property of the window object:

JS Browser memory usage function in kilobytes

Now let’s call our main() method with the ordinary function and generator function to calculate the memory usage of each.

We first run our standard JS function main(bigAmountOfItems, 2000000).

Memory difference after iterating over 2 billion items with an ordinary function

Next will execute the generator function main(bigAmountOfItemsGenerator, 2000000).

Memory difference after iterating over 2 billion items with a generator function

As you can see, the standard JS function shows a memory increase of ~46.5 kilobytes whereas the generator increase was only ~0.125 kilobytes. This is because we didn’t need to keep all 2000000 items in our RAM with the generator function. The iterator allows us to keep track of the current iteration item and continue to return the next one until the end.

That’s the main thing that allows developers to save memory and to keep track of local variables or inner loops among the generator function without the necessity of outer code to know anything about the inner logic of the function.

Also, browsers work with async / await over generators and promises. But that’s a topic for another article :) I hope you got something useful from the story. Thanks for reading! Have a good life ;)

Tag cloud