加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – 不可变对象的缺点

发布时间:2020-12-16 10:06:52 所属栏目:安全 来源:网络整理
导读:我知道Immutable对象比可变对象提供了几个优点,比起它们比可变对象更易于推理,它们没有随时间变化的复杂状态空间,我们可以自由地传递它们,它们可以制作安全的哈希表键等.所以我的问题是不可变对象的缺点是什么? 解决方法 引自Effective Java: The only rea
我知道Immutable对象比可变对象提供了几个优点,比起它们比可变对象更易于推理,它们没有随时间变化的复杂状态空间,我们可以自由地传递它们,它们可以制作安全的哈希表键等.所以我的问题是不可变对象的缺点是什么?

解决方法

引自Effective Java:

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);

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.

阅读Item 15: Minimize mutability的完整项目

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读