本文介绍了不可变对象如何减少垃圾收集带来的开销?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新手,并且已经从前两个答案中阅读了有关垃圾收集的信息.

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:

问题是如何?垃圾收集与对象的可变性或不可变性有什么关系?

推荐答案

有时候,当对象是不可变的时,分配的资源会更少.

Sometimes you allocate less when objects are immutable.

简单的例子

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

我每次共享 Date 时都必须复制它,因为它是可变的,否则调用者将能够对其进行突变.如果 getDate 被调用很多,分配率将急剧增加,这将给 GC

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

另一方面,Java-8日期是不可变的

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.

这篇关于不可变对象如何减少垃圾收集带来的开销?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 06:48