Sunday, May 22, 2016

When to do shallow copy and deep copy?

Its very simple that if the object has only primitive fields, then obviously you will go for the shallow copy but if the object has references to other objects, then based on the requirement, shallow copy or deep copy should be chosen. What I mean here is, if the references are not modified anytime, then there is no point in going for deep copy. You can just opt shallow copy. But if the references are modified often, then you need to go for the deep copy. Again there is no hard and fast rule, it all depends on the requirement.
What is - Lazy copy
A lazy copy is a combination of both shallow copy and deep copy. When initially copying an object, a (fast) shallow copy is used. A counter is also used to track how many objects share the data. When the program wants to modify the original object, it can determine if the data is shared (by examining the counter) and can do a deep copy at that time if necessary.
Lazy copy looks to the outside just as a deep copy but takes advantage of the speed of a shallow copy whenever possible. It can be used when the references in the original object are not modified often. The downside are rather high but constant base costs because of the counter. Also, in certain situations, circular references can also cause problems.


References -http://www.jusfortechies.com/java/core-java/deepcopy_and_shallowcopy.php

No comments:

Post a Comment