What is the difference between a deep copy and a shallow copy?

深拷贝和浅拷贝之间有什么区别?


Shallow copies duplicate as little as possible. A shallow copy of a collection is a copy of the collection structure, not the elements. With a shallow copy, two collections now share the individual elements.

Deep copies duplicate everything. A deep copy of a collection is two collections with all of the elements in the original collection duplicated.


Breadth vs Depth; think in terms of a tree of references with your object as the root node.

Shallow:

The variables A and B refer to different areas of memory, when B is assigned to A the two variables refer to the same area of memory. Later modifications to the contents of either are instantly reflected in the contents of other, as they share contents.

Deep:

The variables A and B refer to different areas of memory, when B is assigned to A the values in the memory area which A points to are copied into the memory area to which B points. Later modifications to the contents of either remain unique to A or B; the contents are not shared.


In short, it depends on what points to what. In a shallow copy, object B points to object A's location in memory. In deep copy, all things in object A's memory location get copied to object B's memory location.

This wiki article has a great diagram.

http://en.wikipedia.org/wiki/Object_copy

链接地址: http://www.djcxy.com/p/40702.html

上一篇: 如何在angularjs中深入观察数组?

下一篇: 深拷贝和浅拷贝之间有什么区别?