Node.js buffer garbage collection

buf.slice([start[, end]])

Returns a new Buffer that references the same memory as the original, but offset and cropped by the start and end indices.

Note that modifying the new Buffer slice will modify the memory in the original Buffer because the allocated memory of the two objects overlap.

How does garbage collector handle allocated memory if one of the references is gone?

Upvotes: 1

Views: 3645

Answers (2)

wattry
wattry

Reputation: 994

From the Node.js buffer documentation: "The implementation of Buffer#slice() creates a view over the existing Buffer without copying, making Buffer#slice() far more efficient.". This means that the buffers reference the same memory location resulting in the overlap. Only once all references to the buffer have been removed, can the memory be reallocated by the garbage collector (gc). When the gc runs, it will delete the buffers that have no references and return the memory to the respective pools.

Node buffers vary in behavior depending on how you initialized them. If you used the new Buffer() methods, they are now deprecated and should revisit the docs. You should use the buffer alloc(), bufferUnsafe() and bufferUnsafeSlow() methods.

Upvotes: 1

Thomas Lomas
Thomas Lomas

Reputation: 1553

When you perform a slice on a Buffer, you are only creating a new reference to the original buffer, which starts and ends at different points.

If you change the original buffer, the sliced reference will also change.

What this means is that the entire chunk of memory won't be available for garbage collection until all references (sliced or not) are gone.

Hope this answers your question.

Upvotes: 6

Related Questions