Search code examples
node.jsmemory-efficient

How many actual bytes of memory node.js Buffer uses internally to store 1 logical byte of data?


Node.js documentations states that:

A Buffer is similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap.

Am I right that all integers are represented as 64-bit floats internally in javascript?

Does it mean that storing 1 byte in Node.js Buffer actually takes 8 bytes of memory?

Thanks


Solution

  • Buffers are simply an array of bytes, so the length of the buffer is essentially the number of bytes that the Buffer will occupy.

    For instance, the new Buffer(size) constructor is documented as "Allocates a new buffer of size octets." Here octets clearly identifies the cells as single-byte values. Similarly buf[index] states "Get and set the octet at index. The values refer to individual bytes, so the legal range is between 0x00 and 0xFF hex or 0 and 255.".

    While a buffer is absolutely an array of bytes, you may interact with it as integers or other types using the buf.read* class of functions available on the buffer object. Each of these has a specific number of bytes that are affected by the operations.

    For more specifics on the internals, Node just passes the length through to smalloc which just uses malloc as you'd expect to allocate the specified number of bytes.