Node.js buffer garbage collection

和自甴很熟 提交于 2019-12-13 01:27:51

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/36817641/node-js-buffer-garbage-collection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!