不可变对象的缺点 [英] Disadvantages of Immutable objects

查看:54
本文介绍了不可变对象的缺点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道不可变对象比可变对象具有多个优点,例如比可变对象更容易推理,它们不具有随时间变化的复杂状态空间,我们可以自由传递它们,并使用安全的哈希表键等等等等.所以我的问题是不可变对象的缺点是什么?

I know that Immutable objects offer several advantages over mutable objects like they are easier to reason about than mutable ones, they do not have complex state spaces that change over time, we can pass them around freely, they make safe hash table keys etc etc.So my question is what are the disadvantages of immutable objects??

推荐答案

引用有效的Java :

不可变类的唯一真正的缺点是它们需要一个 每个不同值的单独对象.创建这些对象可以是 昂贵,特别是如果它们很大.例如,假设您 有一个百万位的BigInteger,您想更改其低阶 位:

The only real disadvantage of immutable classes is that they require a separate object for each distinct value. Creating these objects can be costly, especially if they are large. For example, suppose that you have a million-bit BigInteger and you want to change its low-order bit:

BigInteger moby = ...; 
moby = moby.flipBit(0);

flipBit方法 创建一个新的BigInteger实例,该实例也长一百万个位, 与原始版本的区别仅在于一点点.手术需要时间 和空间与BigInteger的大小成正比.对比一下 java.util.BitSet.与BigInteger一样,BitSet任意表示 位的长序列,但与BigInteger不同的是,BitSet是可变的.这 BitSet类提供了一种允许您更改状态的方法 恒定时间内有一个百万位实例的一小部分.

The flipBit method creates a new BigInteger instance, also a million bits long, that differs from the original in only one bit. The operation requires time and space proportional to the size of the BigInteger. Contrast this to java.util.BitSet. Like BigInteger, BitSet represents an arbitrarily long sequence of bits, but unlike BigInteger, BitSet is mutable. The BitSet class provides a method that allows you to change the state of a single bit of a millionbit instance in constant time.

第15项:最小化可变性

这篇关于不可变对象的缺点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆