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.
To test both functions I will create a
main() function that will check how the memory usage changed after each iteration over the items.
I calculated the memory usage with a simple function that utilizes the
performance property of the
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
Next will execute the 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 ;)