JS垃圾回收器是否清除堆栈内存? [英] Does the JS garbage collector clear stack memory?

查看:364
本文介绍了JS垃圾回收器是否清除堆栈内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于这个问题的第一个评论:
什么使这个函数运行速度慢得多?



垃圾收集器是否扫描堆栈内存?从我读过的内容来看,通常gc不会这样做。

在这个问题之后,我想象一下堆栈和堆内存之间没有物理差异;有虚拟的部门吗?我的意思是:当理论上使用所有堆栈内存而不导致溢出并在此之后将新内存分配给对象时会发生什么?

有人可以详细说明这是如何实际运作的吗?
谢谢。

解决方案


垃圾收集器是否扫描堆栈内存?
blockquote>

没有。 垃圾收集器只能管理堆内存。当程序返回到堆栈帧时,堆栈中的所有值都需要再次使用,所以它们不能被收集。





当然,程序的哪些部分会进入堆栈,进入堆不容易在像JavaScript这样的动态语言中做出决定。一些优化允许在堆栈上分配对象,并且闭包可能需要在堆中分配变量环境。


我想象那里堆栈和堆内存之间没有物理差异;是否有一个虚拟部门?


确实如此。 堆栈只是计算机内存(通常为固定大小)的区域,专用于某些进程的堆栈。事实上,你的记忆中有很多堆栈,每个线程都有一个堆栈,解释器(例如JS)也创建自己的堆栈。


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.

解决方案

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.

这篇关于JS垃圾回收器是否清除堆栈内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆