How does the Java – immutable object help reduce the overhead caused by garbage collection?

I'm a novice. I've seen garbage collection in the previous two answers here

Now, even if programmers have to create new objects, compared with using existing objects (in multi-threaded applications), it is now proved to use immutable objects. This tutorial means that the cost of object creation can be compensated by reducing memory overhead to garbage collection, and code can be eliminated to protect variable objects from thread interference and memory consistency errors:

What's the problem? What is the relationship between garbage collection and the variability or invariance of items?

Solution

Sometimes, when objects are immutable, you can allocate less space

Simple example

Date getDate(){
   return copy(this.date);
 }

Every time I share it because it is mutable or the caller will be able to mutate it must copy the date If getdate is called a lot, the allocation rate will increase greatly, which will put pressure on GC

On the other hand, java-8 dates are immutable

LocalDate getDate(){
  return this.date;
}

Note that I don't need to copy the date (assign a new object) because it's immutable (I'm happy to share the object with you because I know you can't mutate)

Now you may consider how to apply it to "useful" or complex data structures without causing a large number of allocations (due to defensive copies). You are absolutely right, but there is an art called functional programming and persistent data structures (i.e. you get this is an illusion, it is a new copy, and the copy is shared a lot from the original)

Not surprisingly, most functional languages (all languages I know) are garbage collected

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>