Does a perpetually suspended function generator have performance costs?
For example, the code below will continually yield
values until the value of d
in the for
loop is reached.
For the purposes of the question, we intentionally prevent the generator from reaching the status of done
. Is there a resource cost in doing this? It would, of course, theoretically be easy to indicate to the generator that we are in fact done
with it, but does it even matter? Why not just have it eternally suspended until it needs to be used again?
var fruits = ['apple', 'pear', 'strawberry']
function* fruitGenerator(items) {
var numberOfItems = items.length
var i = 0
while (true) {
yield items[i]
i++
if (i === numberOfItems) {
i = 0
}
}
}
var multipleFruits = fruitGenerator(fruits)
for (var d = 0 ; d < 10; d++) {
console.log(multipleFruits.next())
}
For all intents and purposes, let's just assume that for this example, I cannot use a regular for
loop.
Generator functions have their own execution context which must be restored each time a generator function is resumed. When a generator function is not being executed, its execution context is stored in an internal property slot, [[GeneratorContext]]
, of the geerator object.
In the sense are there any overheads whatsoever in using generator functions, the answer is yes, there are they those required to restore a saved execution. Would you be able to detect them using profiling tools, probably not - all JavaScript operations have execution steps defined in standards, and restoring and saving execution contexts is unlikely to be more significant than other steps in JavaScript operation.
In the sense do generator functions consume execution time when not being used, the asnwer is no. Generator objects are objects residing in memory until used.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With