In theory there would be no difference between mutating an existing memory area and allocating new memory to write to it. The number of bytes written to RAM are the same.
It's not the same, you need to allocate new memory, if it's on the heap then (depending on your allocator/OS etc) you will be making a syscall, which means context switch, cache eviction etc.
That means a difference of ~300 cycles before you can even start working with the cache line you pull from main memory.
I think frameworks like React should explicitly demand that state and props will be referentially compared to optimize the rendering.
so you mean bloody expensive ? seriously, if everybody thinks like you no surprise the current web crawls on beastly computers.
The only way to address it is with extensive pooling and heuristics.
Or you can just mutate.
Really it's no wonder that the web is so slow if the common conception is that allocating is no big deal. If you really want to do performance right allocations should be at the top of your list right next to how cache friendly your data structures are.
When a GC allocates memory all it does is check if there is enough memory in the "young generation" if yes it will increment a pointer and then it will just return the last position in the young generation. If there is not enough memory in the young generation the GC will start traversing the GC root nodes on the stack and only the "live" memory has to be traversed and copied over to the old generation. In other words in the majority of cases allocation memory costs almost as much as mutating memory.
Mutable language GC's like JS or Java's aren't necessarily built for this compared to GHC. And even discounting all that, things like stack memory, cache, etc all make a huge difference in real world performance. GC's have come a long way, but there is still a gap in performance.
"Immutable" data structures are not just objects that never get mutated, they're different manners of organizing the bytes.
However, most JS runtime have a generational GC so an allocation isn't remotely as costly as an allocation in C or Rust.
[1] https://reactjs.org/tutorial/tutorial.html#why-immutability-...
Afaik you don't have to. It just makes things easier since state changes can be detected through shallow reference comparisons. There is even the shouldComponentUpdate() hook to allow the user to detect state changes which did not trigger a whole state object change.
When you use `Object.assign()` then you're doing it, but you don't have to use that, and probably shouldn't.
This kind of performance optimization, especially outside of game engines seem unnecessary.