0

If I have an array of 1000 elements and I set the array length to 10, where the other element will go? Will that cause a memory leak?

gfxmoda
  • 21
  • 4

4 Answers4

2

where the other element will go?

The properties 10 to 999 will get deleted when you assign .length = 10.

Setting .length = 0 is a well-known solution for emptying an array.

Will that cause a memory leak?

No, they will get garbage-collected normally.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
2

The ECMAScript specs are saying that the elements are deleted:

Reducing the value of the "length" property has the side-effect of deleting own array elements whose array index is between the old and new length values.

Also, ArraySetLength is specifying that a Delete is performed for whose numeric value is greater than or equal to newLen, in descending numeric index order

So no - there will be no memory leak if you reduce the length of an array.

0

Using [] or new Array(10000) will both create Arrays with exactly the same memory footprint. Just the length has a different initial value.

JavaScript is different from other languages, where an array of size n will have n storage spaces reserved for the elements.

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
Alwani Anis
  • 260
  • 3
  • 11
0

if array length is set to smaller value then other values gets removed/deleted from the array.

lets say

let arr = [1,2,3];

then if you set

arr.length = 1;

then the arr will have only [1], other elements gets removed from the array.

Amruth
  • 5,792
  • 2
  • 28
  • 41