为什么必须进行垃圾收集? [英] Why is garbage collection necessary?

查看:103
本文介绍了为什么必须进行垃圾收集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设堆上的对象超出范围.范围结束后,为什么程序无法立即释放内存?或者,如果我们有一个指向被新对象的地址替换的对象的指针,为什么程序在分配新对象之前不能取消分配旧对象?我猜想不立即释放它,而是在以后的某个时间点以异步方式完成释放会更快,但我不确定.

Suppose that an object on the heap goes out of scope. Why can't the program free the memory right after the scope ends? Or, if we have a pointer to an object that is replaced by the address to a new object, why can't the program deallocate the old one before assigning the new one? I'm guessing that it's faster not to free it immediately and instead have the freeing be done asynchronously at a later point in time, but I'm not really sure.

推荐答案

为什么必须进行垃圾收集?

Why is garbage collection necessary?

这不是严格必要的.只要有足够的时间和精力,您就可以始终将依赖垃圾回收的程序转换为不需要垃圾回收的程序.

It is not strictly necessary. Given enough time and effort you can always translate a program that depends on garbage collection to one that doesn't.

通常,垃圾回收需要权衡.

In general, garbage collection involves a trade-off.

一方面,垃圾回收使您可以编写应用程序而不必担心内存分配和释放的细节.(以及由于重新分配逻辑错误而导致的调试崩溃和内存泄漏的痛苦.)

On the one hand, garbage collection allows you to write an application without worrying about the details of memory allocation and deallocation. (And the pain of debugging crashes and memory leaks caused by getting the deallocation logic wrong.)

垃圾回收的缺点是您需要更多的内存.如果没有足够的可用空间 1 ,则典型的垃圾收集器效率不高.

The downside of garbage collection is that you need more memory. A typical garbage collector is not efficient if it doesn't have plenty of spare space1.

相反,如果您进行手动内存管理,则可以对应用程序进行编码,以在不再使用堆对象时释放它们.此外,在GC正在执行其操作时,您不会感到尴尬的暂停".

By contrast, if you do manual memory management, you can code your application to free up heap objects as soon as they are no longer used. Furthermore, you don't get awkward "pauses" while the GC is doing its thing.

手动内存管理的缺点是您必须编写决定何时调用免费的代码,并且必须获得它是正确的.此外,如果您尝试通过引用计数来管理内存:

The downside of manual memory management is that you have to write the code that decides when to call free, and you have to get it correct. Furthermore, if you try to manage memory by reference counting:

  • 每当分配指针或变量超出范围时,您都有增加和减少引用计数的代价,
  • 您必须处理数据结构中的周期,并且
  • 当您的应用程序是多线程的并且必须处理内存缓存,同步等时,情况更糟.

就其价值而言,如果您使用体面的垃圾收集器并对其进行适当的调整(例如,为其提供足够的内存等),则将它们应用于大型应用程序时,GC和手动存储管理的CPU成本是可比的.

For what it is worth, if you use a decent garbage collector and tune it appropriately (e.g. give it enough memory, etc) then the CPU costs of GC and manual storage management are comparable when you apply them to a large application.

参考:

  • "The measured cost of conservative garbage collection" by Benjamin Zorn

1-这是因为现代收集器的主要成本是遍历和处理非垃圾对象.如果没有太多的垃圾,因为您对堆空间的处理不当,则GC会做很多工作而几乎没有回报.有关分析,请参见 https://stackoverflow.com/a/2414621/139985 .

这篇关于为什么必须进行垃圾收集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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