简体   繁体   English

为什么像 HashMap 或 LinkedList 这样的 Java 容器不重用在添加新元素时被删除的内部节点?

[英]Why don`t Java containers like HashMap or LinkedList reuse internal Nodes which were deleted when adding new elements?

A class like LinkedList stores objects in instances of an internal class called Node.像 LinkedList 这样的 class 将对象存储在称为 Node 的内部 class 实例中。 Each time a new element is added, a new Node is created with the 'new' operator.每次添加新元素时,都会使用“new”运算符创建一个新节点。 Why does not it try to reuse Nodes that were previously created for elements which were later deleted?为什么它不尝试重用先前为后来删除的元素创建的节点? The LinkedList could store a list of nodes created for elements that were deleted and try to reuse them when new elements are added. LinkedList 可以存储为删除的元素创建的节点列表,并在添加新元素时尝试重用它们。 Moreover, it could store the unused Nodes under a soft reference so as not to waste memory. Reusing Nodes should reduce the load on the garbage collector and decrease the number of its invocations.此外,它可以将未使用的节点存储在软引用下,以免浪费 memory。重用节点应该减少垃圾收集器的负载并减少其调用次数。 Why does not Java do that?为什么 Java 不那样做?

Moreover, it could store the unused Nodes under a soft reference so as not to waste memory. Reusing Nodes should reduce the load on the garbage collector and decrease the number of its invocations.此外,它可以将未使用的节点存储在软引用下,以免浪费 memory。重用节点应该减少垃圾收集器的负载并减少其调用次数。

Java's garbage collection is optimized for the case of having many short-lived objects over having longer-lived objects -- especially for small objects like linked list nodes. Java 的垃圾收集针对具有许多寿命较短的对象而不是寿命较长的对象的情况进行了优化——尤其是对于像链表节点这样的小对象。 Due to the generational approach of Java's GC, it usually performs better to throw away existing objects and reallocate them.由于 Java GC 的分代方法,丢弃现有对象并重新分配它们通常性能更好。 Additionally, maintaining soft references can often add noticeable overhead.此外,维护软引用通常会增加明显的开销。

The approach you describe would make things worse, not better, for most applications.对于大多数应用程序,您描述的方法会使事情变得更糟,而不是更好。 In general, the Java garbage collector is extremely good at its job, and trying to manually manage Java objects for memory reasons rarely beats it.一般来说,Java 垃圾收集器非常擅长它的工作,并且出于 memory 的原因尝试手动管理 Java 个对象很少能打败它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM