Search code examples
javascriptnode.jsv8

Will memory usage change between `await Promise.all` and `X = await Promise.all`?


For example, if each of the promises resolved with a value that has 1 byte, and the number of promises is 100,000

await Promise.all(promises) // not capture the return value

X = await Promise.all(promises) // capture the return value

Obviously, the latter one will cost at least 100,00 byte, but how about the first one?
Will V8 does some optimizations to reduce memory usage for the first one?


Solution

  • Not assigning the result from await Promise.all() just means that the result will be immediately eligible for garbage collection. The result is still created by Promise.all() as it doesn't know whether you're going to use it or not.

    So, whether that creates any difference from your X = await Promise.all(...) purely depends upon how soon X is available for garbage collection. If you use the result immediately and then X goes out of scope and is quickly eligible for garbage collection, then there's probably no difference in the memory usage profile as that value will be created and then garbage collected at a similar time either way.

    If, on the other hand, X stays around for a long time (like gets stored in some lasting data structure) then of course, its memory usage will endure for awhile.

    Will V8 does some optimizations to reduce memory usage for the first one?

    No.