如果我将 javascript 数组长度更改为较小的值,这会导致内存泄漏吗?
if I alter javascript array length to a smaller value would this cause a memory leak?
如果我有一个包含 1000 个元素的数组,并且我将数组长度设置为 10,那么其他元素会去哪里?这会导致内存泄漏吗?
使用[]
或new Array(10000)
将创建具有完全相同内存占用的数组。只是长度有不同的初始值。
JavaScript与其他语言不同,一个大小为n的数组会为元素保留n个存储空间。
where the other element will go?
属性 10
到 999
将在您分配 .length = 10
时被删除。
设置 .length = 0
是 emptying an array 的众所周知的解决方案。
Will that cause a memory leak?
不会,它们会被正常回收。
如果数组长度设置为较小的值,则其他值将从数组中获取 removed/deleted。
让我们说
let arr = [1,2,3];
那么如果你设置
arr.length = 1;
那么 arr
将只有 [1]
,其他元素从数组中删除。
ECMAScript specs 表示元素是 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.
此外,ArraySetLength 指定为 whose numeric value is greater than or equal to newLen, in descending numeric index order
执行 Delete
所以不会 - 如果您减少数组的长度,就不会有内存泄漏。
如果我有一个包含 1000 个元素的数组,并且我将数组长度设置为 10,那么其他元素会去哪里?这会导致内存泄漏吗?
使用[]
或new Array(10000)
将创建具有完全相同内存占用的数组。只是长度有不同的初始值。
JavaScript与其他语言不同,一个大小为n的数组会为元素保留n个存储空间。
where the other element will go?
属性 10
到 999
将在您分配 .length = 10
时被删除。
设置 .length = 0
是 emptying an array 的众所周知的解决方案。
Will that cause a memory leak?
不会,它们会被正常回收。
如果数组长度设置为较小的值,则其他值将从数组中获取 removed/deleted。
让我们说
let arr = [1,2,3];
那么如果你设置
arr.length = 1;
那么 arr
将只有 [1]
,其他元素从数组中删除。
ECMAScript specs 表示元素是 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.
此外,ArraySetLength 指定为 whose numeric value is greater than or equal to newLen, in descending numeric index order
Delete
所以不会 - 如果您减少数组的长度,就不会有内存泄漏。