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??
Quoting from 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 theBigInteger
. Contrast this tojava.util.BitSet
. LikeBigInteger
,BitSet
represents an arbitrarily long sequence of bits, but unlikeBigInteger
,BitSet
is mutable. TheBitSet
class provides a method that allows you to change the state of a single bit of a millionbit instance in constant time.
Read the full item on Item 15: Minimize mutability
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With