Search code examples
javascriptnode.jsbuffer

Why is it necessary to allocate memory for buffer when it is created?


Javascript being a dynamic language, why is it mandatory to mention the size of the buffer when it is created?

var buffer = new Buffer(10);

Solution

  • I should think it's likely that Buffer instances use typed arrays behind the scenes for efficiency, or even low-level arrays (as Buffer is a native part of Node, which is written in C++, not JavaScript). Indeed, looking at node_buffer.cc, that appears to be the case. Typed arrays or low-level arrays are fixed-size, allocate-on-creation structures.


    Side note: new Buffer(size) is deprecated; use Buffer.alloc instead.