Does the JS garbage collector clear stack memory?

Following the first comment on this question: What makes this function run much slower?

Does the garbage collector sweep stack memory? From what I've read, usually gc's don't do this.
Following this question, I imagine that there is no physical difference between stack and heap memory; is there a virtual division? What I mean is: what happens when theoretically all stack memory is used without causing an overflow and new memory is allocated to an object after that?

Could someone elaborate on how this actually works? Thanks.

Answers:

Answer

Does the garbage collector sweep stack memory?

No. The garbage collector does only manage heap memory. All values on the stack are expected to be needed again when the program returns to that stack frame, so they must not be collected. The references from the stack into the heap are indeed considered alive.

The stack memory is cleared automatically when a function exits.

Of course, what parts of a program go onto the stack and which go into the heap is not easy to decide in a dynamic language like JavaScript. Some optimisations allow objects to be allocated on the stack, and closures might require that variable environments are allocated in the heap.

I imagine that there is no physical difference between stack and heap memory; is there a virtual division?

That's true. "The stack" is just a (typically fixed-size) region of your computers memory, dedicated to be "the stack" by some process. Indeed there are many stacks living in your memory, one for each thread, and interpreters (e.g. for JS) create their own stacks as well.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.