Friday, March 11, 2016

Deep vs Shallow Copy

Friday, March 11th 2016

In programming, there are generally two ways to copy things. You can create a shallow copy of data  and you can create a deep copy of data. Typically, a shallow copy of data makes a reference to where the original data is in memory, whereas a deep copy copies the original data in full and creates memory allocation for that copy, specifically.




Actual examples of each in JS:
//shallow copy                                                          //deep copy
var arr = [1,2,3];                                                       var arr = [1,2,3];
var arr2 = arr;                                                            var arr2 = [];
console.log(arr2); //[1,2,3]                                        for(var i = 0; i < arr.length; i++) {
arr[0]++;                                                                          arr2[i] = arr[i];
console.log(arr2); //[1,2,3]                                        }
                                                                                  console.log(arr2); //[1,2,3];
                                                                                  arr[0]++;
                                                                                  console.log(arr2); //[1,2,3];

In summary, a shallow copy is a reference to the memory of the original whereas a deep creates new memory for a copy of the original. Most related bugs aren't actually a result of shallow/deep copies, but rather confusion regarding reference by type vs reference by value.

References
http://stackoverflow.com/questions/3947227/deep-copy-of-an-object-array
http://geniuscarrier.com/copy-object-in-javascript/
http://stackoverflow.com/questions/184710/what-is-the-difference-between-a-deep-copy-and-a-shallow-copy

No comments:

Post a Comment