简体   繁体   中英

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. Each time a new element is added, a new Node is created with the 'new' operator. 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. 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. Why does not Java do that?

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.

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. Due to the generational approach of Java's GC, it usually performs better to throw away existing objects and reallocate them. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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