Reputation: 301
I know that JS engine automatically delete from memory "unused" objects. So if we have some enormous object and want to free memory we have to do something like this:
largeObject = null
And if we haven't any other links to our object it will be removed by engine soon. It's clear. But what if we have enormous string. For example we have read it from file:
largeString = fs.readFileSync('bigdata.txt', 'utf8')
Can we tell engine that we will not use this string?
largeString = null
It's work only for objects, but string is a primitive type.
Also will it work with buffers:
let largeData = rs.readFileSync('bigdata')
/* Some code */
largeData = null
JS engine should understand that we will not use this buffer and free it. But Buffer
is inherited from Int8Array
and the last is just view for some ArrayBuffer
. Which is accessable by largeData.buffer
. Of course after largeData = null
we lose access to this ArrayBuffer and so memory should be free in some time. Am I right in this purpose?
I know, that JS is not language about memory manipulations, but in my opinion very important to understand how engine frees memory to minimize risk of the memory lick.
Upvotes: 0
Views: 1030
Reputation: 6597
But what if we have enormous string.
Strings are primitive values just like numbers. You can't have references to strings. However, strings can be deallocated when they are not reachable.
JS engine should understand that we will not use this buffer and free it. But
Buffer
is inherited fromInt8Array
and the last is just view for someArrayBuffer
. Which is accessable bylargeData.buffer
. Of course afterlargeData = null
we lose access to thisArrayBuffer
and so memory should be free in some time. Am I right in this purpose?
You are right. Because the only way to access the buffer is through largeData.buffer
, if there are no references to largeData
, the buffer can also be deallocated.
It's worth noting that the EcmaScript Specification doesn't specify when/how garbage collection happens. In fact, an engine that never collects garbage may be completely spec-compliant. In practice, however, most engines do that, to prevent memory leaks.
Upvotes: 1