0

I found some issue with .length = 0 and now if I change to = [], all things are working well in my javascript project.

var arr = [1,2,3,4,5];
alert(arr);
arr = [];
alert(arr);
arr.length = 0;
alert(arr);

But I have one question if I use arr = [], when the memory of [1,2,3,4,5] disappear? If the array is big and I use [] lots of times it will cause memory lack problems.

artgb
  • 3,177
  • 6
  • 19
  • 36
  • *"I found some issue with `.length = 0`"* Care to share? – T.J. Crowder Aug 30 '17 at 15:55
  • You can see my stack problem https://stackoverflow.com/questions/45924788/angular-appending-is-fast-but-destroying-is-slow1-second here I changed .length =0 to = [] and solved the problem – artgb Aug 30 '17 at 15:57

2 Answers2

0

But I have one question if I use arr = [], when the memory of [1,2,3,4,5] disappear?

Whenever the JavaScript engine gets around to releasing it, which it will do as and when necessary once nothing has a reference to it anymore. The details vary depending not only on the JavaScript engine involved, but on where that code appears and how frequently it's run (e.g., how aggressively it ends up getting optimized). If it matters (e.g., that's run a lot), it'll get reclaimed really quickly.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • I want to you to describe why this post is available https://stackoverflow.com/questions/4804235/difference-between-array-length-0-and-array according to your answer. – artgb Aug 30 '17 at 16:07
  • @artgb: I don't understand the question in your comment...? – T.J. Crowder Aug 30 '17 at 16:08
  • You said if I use arr = [] the memory space will disappear automatically and why .length = 0 is needed? – artgb Aug 30 '17 at 16:10
  • @artgb: If you've done `arr = []`, you **don't** need `arr.length = 0`. – T.J. Crowder Aug 30 '17 at 16:10
  • I see many codes arr.length = 0 and why they did not used arr = []? is it their selection? – artgb Aug 30 '17 at 16:12
  • @artgb: It totally depends on what you want to do. Consider: If you do `var a = [1, 2, 3]; var b = a; a = [];`, then `a` refers to a new, empty array and `b` still refers to the old array (they no longer refer to the same array) which still has the entries. But if you do `var a = [1, 2, 3]; var b = a; a.length = 0;` it *modifies* that same array, removing the entries from it, and `a` and `b` still refer to the same (now empty) array. – T.J. Crowder Aug 30 '17 at 16:20
  • 1
    Thanks, I understood your idea just now – artgb Aug 30 '17 at 16:22
0

Your question comes down to how the various Javascript engines perform garbage collection. While they each do it slightly differently, the key to allowing them cleanup allocated memory is to make sure there are no lingering references (including through a closure or async call) remaining to the original array.

Gets trickier if that array has been passed into another function that is still on the stack or itself in a closure.

ballenf
  • 894
  • 10
  • 19