It makes the code icky and hard to debug, and you can simply return new immutable objects for every state change.
EDIT: why not just create a new object and reassign variable to point to the new object
It makes the code icky and hard to debug, and you can simply return new immutable objects for every state change.
EDIT: why not just create a new object and reassign variable to point to the new object
I’m gonna hazard a guess, just cause I’m curious, that you’re coming from JavaScript.
Regardless, the answer’s basically the same across all similar languages where this question makes sense. That is, languages that are largely, if not completely, object-oriented, where memory is managed for you.
Bottom line, object allocation is VERY expensive. Generally, objects are allocated on a heap, so the allocation process itself, in its most basic form, involves walking some portion of a linked list to find an available heap block, updating a header or other info block to track that the block is now in use, maybe sub-dividing the block to avoid wasting space, any making any updates that might be necessary to nodes of the linked list that we traversed.
THEN, we have to run similar operations later for de-allocation. And if we’re talking about a memory-managed language, well, that means running a garbage collector algorithm, periodically, that needs to somehow inspect blocks that are in use to see if they’re still in use, or can be automatically de-allocated. The most common garbage-collector I know of involves tagging all references within other objects, so that the GC can start at the “root” objects and walk the entire tree of references within references, in order to find any that are orphaned, and identify them as collectable.
My bread and butter is C#, so let’s look at an actual example.
Even for the most basic edit operation, immutable copying is slower by more than 7 times, and (obviously) allocates more memory, which translates to more cost to be spent on garbage collection later.
Let’s scale it up to a slightly-more realistic immutable data structure.
Not only is performance worse, but it drops off exponentially, as you scale out the size of your immutable structures.
Now, all this being said, I myself use the immutable object pattern FREQUENTLY, in both C# and JavaScript. There’s a lot of problems you encounter in business logic that it solves really well, and it’s basically the ideal type of data structure for use in reactive programming, which is extremely effective for building GUIs. In other words, I use immutable objects a ton when I’m building out the business layer of a UI, where data is king. If I were writing code within any of the frameworks I use to BUILD those UIs (.NET, WPF, ReactiveExtensions) you can bet I’d be using immutable objects way more sparingly.
I seriously appreciate you taking the time to do this. Good info.