Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is NSNumber immutable?

Tags:

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.

like image 770
Proud Member Avatar asked Apr 28 '11 13:04

Proud Member


2 Answers

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.

like image 198
Eiko Avatar answered Sep 28 '22 00:09

Eiko


Immutable numbers save space. Assume that your program creates many NSNumbers, 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.

like image 42
9000 Avatar answered Sep 28 '22 01:09

9000