Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do Immutable Objects help decrease overhead due to Garbage Collection?

I am a newb, and I have read about Garbage Collection from the first two answers here.

Now justifying the use of Immutable Objects even if the programmer has to create new objects, as compared to using existing objects (in multi-threaded applications), this tutorial says that the cost of object creation is made up for by the decrease in memory overhead due to garbage collection, and the elimination of code to protect mutable objects from threads interference and memory consistency errors:

The impact of object creation is often overestimated, and can be offset by some of the efficiencies associated with immutable objects. These include decreased overhead due to garbage collection, and the elimination of code needed to protect mutable objects from corruption.

The question is how? What does Garbage Collection have to do with Mutability or Immutability of objects?

like image 459
Solace Avatar asked Feb 13 '16 19:02

Solace


1 Answers

Sometimes you allocate less when objects are immutable.

Simple example

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

I have to copy Date every time I share it because it is mutable or the caller would be able to mutate it. If getDate get called a lot,the allocation rate will dramatically increase and this would put pressure on the GC

On the other hand, Java-8 dates are immutable

LocalDate getDate(){   return this.date; } 

Notice that I don't need to copy date (allocate a new object) because of immutability ( I am happy to share the object with you because I know that you can't mutate it).

Now you might think how can I apply this to "useful" or complicated data structures without causing massive allocation (due to defensive copies), you are absolutely right, but there is an art called functional programming and persistent data structures ( ie: you get the illusion that it's a new copy where in fact copies share a lot from the original).

One shouldn't be surprised that most functional languages (all the ones that I am aware of) are garbage collected.

like image 188
Sleiman Jneidi Avatar answered Sep 23 '22 17:09

Sleiman Jneidi