Why is NSNumber immutable? Was there a good reason? Because now I am thinking about creating my own class just for the sake of mutability.
A number is a very basic data type. A number is just that - a number. If you mutate it, it just happens to be something else. A number simply cannot change.
Compare that with more complex data, where the object itself still represents the same thing.
Immutable numbers save space. Assume that your program creates many NSNumber
s, and most of them happen to be small numbers like 0 or 1. With immutable numbers, you only need a handful objects, one for each distinct value. With mutable numbers, you have as many objects as you have numbers.
Immutable numbers are easy to share. Assume that you wrap a primitive number (like int
) with an NSNumber
. With immutable NSNumber
, the compiler is always sure that the values match, so it can unwrap it and pass the primitive value to function that expect a primitive value. With mutable NSNumber
, you can't be sure than another thread did not change the value, and have to actually unwrap it every time, or even think about synchronization. This becomes more costly if the value is passed further and further in nested calls.
Immutable objects have many other useful properties: they are good hash keys, their lifetime and scope is easier to determine, etc. Many functional languages, e.g. Erlang or XSLT, only have immutable data structures.
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