> Why would I want to have a thing in memory, copy it to more memory, modify the copy, then free up the original memory every time?
You don't do that, runtime does that for you.
The main benefit is better assumptions about code you write. The prime example is how different languages handle object construction and modification:
var date = new Date(2022, 11, 21)
var other = date.addDays(10)
The question is: what do `date` and `other` contain?
Depending on the language the answer may surprise you. Some languages modify `date`. Others don't. And you never know which of the methods exposed on an object modify it unless you read documentation. Neither the compiler nor the type system can help you.
However, if objects are immutable, you are guaranteed that the original object, `date` is never modified. And if you need to use it again, you know it contains the same data without it suddenly changing.
This gives rise to another important property: you can send this to another thread without mutexes or without creating weird synchronization points like Java's AtomicInteger. Since the object cannot be mutated, threads don't have to fight for exclusive access to read it.
You don't do that, runtime does that for you.
The main benefit is better assumptions about code you write. The prime example is how different languages handle object construction and modification:
The question is: what do `date` and `other` contain?Depending on the language the answer may surprise you. Some languages modify `date`. Others don't. And you never know which of the methods exposed on an object modify it unless you read documentation. Neither the compiler nor the type system can help you.
However, if objects are immutable, you are guaranteed that the original object, `date` is never modified. And if you need to use it again, you know it contains the same data without it suddenly changing.
This gives rise to another important property: you can send this to another thread without mutexes or without creating weird synchronization points like Java's AtomicInteger. Since the object cannot be mutated, threads don't have to fight for exclusive access to read it.