Leon Braun
Leon Braun

Reputation: 415

Potentioal memory leak with spread operator?

I'm just wondering if the following code snippet is a potential memory leak.

let arrOfObj = [
    { a: 0, b: 0 }
]

const copy = [ ...arrOfObj ]
copy[0].a = 5;
console.log(arrOfObj)
// [ { a: 5, b: 0 } ]
console.log(copy)
// [ { a: 5, b: 0 } ]

arrOfObj = []
console.log(arrOfObj)
// []
console.log(copy)
// [ { a: 5, b: 0 } ]

The spread operator will only do a shallow copy, so the object inside the array would be a reference. But where did javascript get the values in the last log? Will they garbage collected as I empty the array?

Upvotes: 1

Views: 1300

Answers (1)

Kanishk Anand
Kanishk Anand

Reputation: 1702

No, there is no memory leak. Breaking down the steps for better explanation:

  1. const copy = [...arrOfObj] : allocates space in memory heap and assign it to copy variable. Since, spread performs shallow copy, the object reference is still same inside of the array.
  2. copy[0].a = 5; : updates the value of the object inside of copy array. Since, the reference to object is same for both copy and arrOfObj, it is reflected in both the arrays.
  3. arrOfObj = [] : allocates space in memory heap for [] and assigns it to arrOfObj variable. This does not imply that copy loses its reference to the array you created earlier. copy still points to the older memory reference. Hence, copy prints out the older array containing object, and arrOfObj prints empty array.

To ellaborate more on this, even if you do the following, copy would still point to older memory reference :

let arrOfObj = [
    { a: 0, b: 0 }
]

// instead of spread, assign it directly 
const copy = arrOfObj;
copy[0].a = 5;
console.log(arrOfObj)
// [ { a: 5, b: 0 } ]
console.log(copy)
// [ { a: 5, b: 0 } ]

// assign empty array to 'arrOfObj'
arrOfObj = []
console.log(arrOfObj)
// []
console.log(copy)
// [ { a: 5, b: 0 } ] => still prints the array

Also, the older value of arrOfObj "may" get garbage collected (depends on JS engine optimisations)

Upvotes: 3

Related Questions