I just started studying garbage collection recently. When I was trying to answer questions related to node memory release in the Ele.me front-end, I encountered some questions:
let arr = [];
while(true)
arr.push(1);
Infinitely increasing arrays will definitely burst the memory.
let arr = [];
while(true)
arr.push();
I think this is just using arr
all the time, causing arr
to not be released, right?
let arr = [];
while(true)
arr.push(new Buffer(1000));
This is because the size of Buffer
is less than 8k. It will first check whether the memory pool is full, so it should not explode the memory?
var theThing = null
var replaceThing = function () {
var originalThing = theThing
var unused = function () {
if (originalThing)
console.log("hi")
}
theThing = {
longStr: new Array(1000000).join('*'),
someMethod: function () {
console.log(someMessage)
}
};
};
setInterval(replaceThing, 1000)
This is because unused
references originalThing
, so each unused
forms a scope of originalThing
replaceThing
's closure, this closure will not be recycled, so it will always accumulate in the memory?
Because I am not very sure, so I would like someone who knows more to answer, thank you!
The new Buffer is probably not a simple memory explosion problem. The Buffer is allocated outside the V8 heap, so it is actually more serious than the first problem. I just crashed.
The second thing that should be said is that since the array size will not grow, it will not burst the memory.
The reason is mentioned in the third original article
If you still don’t understand, you can read the original discoverer’s article, which explains it in detail.
Infinite loop code will burst the memory wherever it goes, especially single-threaded languages like js, which will directly block and freeze.
I have never used the Buffer type. I am not sure whether it will check the memory pool, but it doesn’t make much sense if it is stuck or not.
I agree with your last statement. Each cycle creates a new object, and the reference address of theThing is constantly changing. Under normal circumstances, the old reference object should be garbage collected, but because unused references the old object originalThing, originalThing Another private variable, so the old object cannot be garbage collected, causing a memory leak.
Is there any difference between the following code? It runs in chrome environment for 30 seconds.
The first picture is the result without this code, and the memory floats at 15M.
The second picture is the result of this code, the memory continues to grow.
I’m not sure, but you can use the memwatch-next package to take a look