There are basically three strategies for copying objects; each has its own advantages and disadvantages.
Shallow Copy
Shallow copy is basically passing references, not actually copying data inside objects. That is why shallow copy is otherwise known as address copy. The main advantage of shallow copy is it is very fast and does not depend on the size of data; however, if the language does not support automatic garbage collection, a shallow copy could lead to a memory leak if not cautious enough. In addition, two object references refer to the same data block on memory after shallow copy.
Deep Copy
This is the opposite of shallow copy. The data from one object is actually copy over to another object. Therefore, two object bare the same data after deep copy and yet there are still different objects! The disadvantage of this strategy is it is slow and expensive; however, deep-copied objects do not depend on each other and are independently modifiable.
Lazy Copy
A lazy copy is a combination of both strategies above. When initially copying an object, a shallow copy is used. A counter is also used to track how many objects share the data. When the program wants to modify an object, it can determine if the data is shared and can do a deep copy if necessary. This is also very similar to 'copy-on-write' technique used in most OSes.
So, how are copy actually implemented in programming languages?
In Java:
Using
clone
method of a class.In Python:
the library's
copy module
provides shallow copy and deep copy of objects through the copy() and deepcopy() functions, respectively. Programmers may define special methods __copy__()
and __deepcopy__()
in an object to provide custom copying implementation.
No comments:
Post a Comment