a = b

Something as simple as this has a lot of stuff going on behind the scenes. In object-oriented programming, it is called object copying. What it means is quite obvious, to create a copy of an existing object.

There can be multiple methods to perform an object copy, such as copying all the fields onto a new object or simply having a reference to the initial object. This leads to the two methods called shallow copy and deep copy.

Shallow copy

Before Shallow Copy Shallow Copying Shallow Copy Done

In shallow copying, a reference to the original object is copied. Due to this, the new object simply points to the old object and they share the same memory space. The contents are shared between the two objects. Any changes made in the new object are reflected in the old object as well. This is much faster than deep copying and is useful when you need to make changes to an object, but don’t need to keep the original values.

Deep copy

Before Deep Copy Deep Copying Deep Done

An alternative is deep copying. In this method, a new object is created and each field of the original object is copied onto the new object. The result is that the two objects do not share contents and each can be modified independent of the other. This is much more expensive than a shallow copy due to the need of actual copying. Deep copying has to be used when you need to make changes to an object, but keep the original values as well.

Methods in some languages

I came across this concept a few days back. I needed to copy a javascript object and was surprised when the original object was getting changed automatically when I changed the new object. I found out that simply copying Javascript objects will perform a shallow copy.

Javascript

Javascript objects are shallow-copied by default. There are a number of ways to perform deep copying as shown in this stackoverflow answer.

A simple way of copying is to JSON encode and decode the object successively. However, this will not work if there are functions in the object.

var newObj = JSON.parse(JSON.stringify(obj))

jQuery also provides support for deep copying.

// Shallow copy
var newObject = jQuery.extend({}, oldObject);

// Deep copy
var newObject = jQuery.extend(true, {}, oldObject);

In the project I was working on, we used AngularJS. It also provides a simple method to deal with deep copying.

angular.copy(sourceObj, destinationObj);

Python

The copy module provides functions for shallow and deep copying.

import copy

# Shallow copy
newObj = copy.copy(obj)

# Deep copy
newObj = copy.deepcopy(obj)