Does the JS garbage collector clear stack memory?

大憨熊 提交于 2020-01-02 11:07:13

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/31698747/does-the-js-garbage-collector-clear-stack-memory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!