最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Could Array.splice lead to memory leak? - Stack Overflow

programmeradmin0浏览0评论

I am currently trying to tackle some memory issue on our Javascript product and I would like to know if there was any chance that removing an item from an array via the splice method could lead to any memory leak or is it equivalent to null the value to remove? Does it change something if the array is stored in the global scope ?

For instance snippet 1:

var myArray = [...]; // init the array;
myArray.splice(indexOfTheItemToRemove, 1);

vs snippet 2 :

var myArray = [...]; // init the array;
var temp = myArray.splice(indexOfTheItemToRemove, 1);
temp.length = 0;
temp = null;

Thank you.

I am currently trying to tackle some memory issue on our Javascript product and I would like to know if there was any chance that removing an item from an array via the splice method could lead to any memory leak or is it equivalent to null the value to remove? Does it change something if the array is stored in the global scope ?

For instance snippet 1:

var myArray = [...]; // init the array;
myArray.splice(indexOfTheItemToRemove, 1);

vs snippet 2 :

var myArray = [...]; // init the array;
var temp = myArray.splice(indexOfTheItemToRemove, 1);
temp.length = 0;
temp = null;

Thank you.

Share Improve this question asked Apr 25, 2016 at 12:21 nicolas-mariennicolas-marien 3195 silver badges13 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 11

According to Mozilla Developer Network:

Some function calls result in object allocation.

So, indeed, there is a memory allocation on splice call.

However, Javascript has a garbage collector, which leads us to the next part of the article:

This is the most naive garbage collection algorithm. This algorithm reduces the definition of "an object is not needed anymore" to "an object has no other object referencing to it". An object is considered garbage collectable if there is zero reference pointing at this object.

Sure enough, as long as we're not assigning the result of the function to a variable, there are no references to it. Therefore, garbage collector could easily free the allocated memory.

We could easily check our assumption by running this piece of code in a browser:

var myArray;
var cycles = 100000;
var delay = 10;

(function step() {
  myArray = ['a', 'b', 'c'];
  myArray.splice(1, 1);

  if (--cycles > 0) {
    setTimeout(step, delay);
  }
}());

We could inspect memory allocations on Chrome Dev Tools' Timeline tab.

The spikes point on a memory deallocation events, and we can see that the memory consumption level returns to its initial state.

So, the answer is: no, there is no memory leak here.

发布评论

评论列表(0)

  1. 暂无评论