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

后端 未结 3 2015
日久生厌
日久生厌 2021-02-01 04:27

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 n

3条回答
  •  眼角桃花
    2021-02-01 04:53

    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.

提交回复
热议问题