垃圾收集不仅可以删除未引用的对象,还可以对堆进行 契约。这是一个非常重要的优化。它不仅使内存使用效率更高(没有未使用的漏洞) ,而且使 CPU 缓存效率更高。高速缓存在现代处理器中是一个非常重要的数量级,它比内存总线更快。
Compacting is done simply by copying bytes. That however takes time. The larger the object, the more likely that the cost of copying it outweighs the possible CPU cache usage improvements.
Fwiw, there's lots of programmer angst about the large object heap not getting compacted. This invariably gets triggered when they write programs that consume more than half of the entire available address space. Followed by using a tool like a memory profiler to find out why the program bombed even though there was still lots of unused virtual memory available. Such a tool shows the holes in the LOH, unused chunks of memory where previously a large object lived but got garbage collected. Such is the inevitable price of the LOH, the hole can only be re-used by an allocation for an object that's equal or smaller in size. The real problem is assuming that a program should be allowed to consume 所有 virtual memory at any time.