The copy-on-modify semantics is a memory management technique that modifies one or more objects, copies those objects to a new location in memory, and makes some modifications there, leaving the original unchanged.
There are two types of copying in R:
- Lazy copying
- Copy-on-modify
Lazy copying
When you assign an existing object to a new variable, the underlying data is not directly copied. Instead, both variables point to the same memory.
Here is the figure that shows that:
In this figure, I explained how you could define a vector “x” and assign that vector to a new variable “y”, and both points to the exact memory location instead of different.
Here is a code example:
x <- c(1, 2, 3)
y <- x
print(y)
Output
[1] 1 2 3
Here, no actual copy of the data in ‘y’ is made. It pointed to the memory location of ‘x’, which has 1 2 3 values.
Copy-on-Modify
The copy-on-modify means it will create an actual copy when the copied variable is modified. In our previous example, when you modify the variable “y”, it will create a new copy with a different memory location.
In the above figure, we first created a lazy copy of data “x”, which is “y” and then created an actual copy by modifying “y”.
Here is a code that explains this figure:
x <- c(1, 2, 3)
y <- x
y[2] <- 4
print(y)
Output
[1] 1 4 3
Before modification, “x” and “y” refer to the same memory location, but after modification, both “x” and “y” refer to different memory locations because now “y” is an independent copied variable with its memory location.
Now, “x” refers to the original data, and “y” refers to the modified copied data.
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.