Home »
Scala
Deep Copy vs. Shallow Copy in Scala
By IncludeHelp Last updated : November 07, 2024
Prerequisite: Scala objects
Object Copy is a way to copy the contents of an object to another object.
There can be two methods to copy objects in Scala,
- Deep Copy
- Shallow Copy
Deep Copy
This a method of copying contents from one object to another object. In this copying technique, the changes made in the copied object are not reflected in the original object.
This shows that the new object copy created and the original object do not share the same memory location.
The figure below illustrates the Deep Copy,
2) Shallow Copy
The shallow copy method of copying contents is a technique in which the changes made in the copied object are reflected in the original object.
This shows that the new object copy created and the original object share the same memory location.
The figure below illustrates the Shallow Copy,
Difference between Shallow and Deep copy
Aspect |
Deep Copy |
Shallow Copy |
Definition |
Creates a complete duplicate of the object, including all nested objects and references. |
Creates a duplicate of the object at the top level only; nested objects are shared with the original. |
Memory Location |
The new object and all nested objects have separate memory allocations. |
The new object has a different memory location, but nested objects share the same memory location as the original. |
Impact of Changes |
Changes made to the copy do not affect the original object or its nested structures. |
Changes made to nested objects within the copy are reflected in the original. |
Copying Process |
Recursive, requires creating copies of all nested objects and references. |
Non-recursive, copies only the top-level structure without copying nested objects. |
Performance |
Slower, due to deep cloning of nested structures. |
Faster, as it only copies the top-level structure and references. |
Typical Use Cases |
Used when a completely independent copy is needed to prevent unintended modifications. |
Used when a quick, top-level copy is sufficient and changes to nested objects are acceptable. |
Complexity |
Higher complexity, especially for objects with deeply nested structures. |
Lower complexity, as only the top-level object is duplicated. |
Memory Usage |
Higher, since a new copy of each nested object is created. |
Lower, as nested objects are shared rather than duplicated. |
Examples |
Commonly used in data manipulation tasks, simulations, and scenarios where isolation is required. |
Common in scenarios where minimal copying is acceptable, like in certain optimizations or quick snapshots. |
Note: Shallow copy is used in object creation for case class in Scala.