3 ms·
I'm afraid I don't get your point. So deep copy is expensive, and if the variable is immutable and has to be changed, it would have to be deep copied. so immut
by jypie 12y ago
I'm afraid I don't get your point.
So deep copy is expensive, and if the variable is immutable and has to be changed, it would have to be deep copied. so immutable is bad?
Or are you trying to say even if it's expensive, the original variable not being corrupted is more important? I know there would be some variables that shouldn't be changed in some programs. but for this need I don't think immutable variables are necessary.
Shouldn't we focus more on the aspect of performance?
Thanks for the input! Please enlighten me.
- yazaddaruvala 12y agoSo, there are two cases. Situation 1: When you want to modify the original structure and use it with only its new value. Situation 2: When you want to share the original with a variation, but continue to use both the new and old structures simultaneously without them effecting each other. So from your comment, you seem to be more familiar with situation 1 and you don't seem to be considering situation 2. However, situation 2 does arise quite often in the building of highly concurrent applications. If you don't understand the benefits/need of situation 2, I can elaborate on that but right now I'm just going to explain the pros/cons of Immutability in both situations. Situation 1: You're correct, immutable data structures are more expensive in this context. They are sometimes preferred anyways (I for example prefer them), but that can and should be debated and I don't want to get into it. However, they are not as expensive as you are making it seem, there almost never needs to be a full deep copy with immutable data structures (keep reading). Situation 2: let x = { y: y, z: 1 }; let x' = copy(x); x'.z = 0; Now when x.y.a changes you don't want x'.y.a to change. To make this guarantee (that x and x' can change state independently of each other) "copy" needs to be an expensive deep copy. ie x' = deep_copy(x); However, if you were guaranteed that y and its nested children were all NEVER going to change (ie Immutable). You can now optimize: x' = shallow_copy(x); Why? because you still have the same guarantee: x.y.a will never change, thus never changing x'.y.a. x and x' are then always independent even with a simple inexpensive shallow copy. Really quick to go back to Situation 1: I hope you see here aswell that the majority of the time, you don't require deep copies. Example, ImmutableMap.put(k,v) just does a shallow copy at depth=0 since you are only mutating the HashMap itself. I am not an expert and so I'm not sure, but I think good ImmutableMaps have been optimized even further. Anyways, I hope that helps.