为什么buffer创建的时候要分配内存?

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

Javascript 作为一种动态语言,为什么在创建缓冲区时必须提及缓冲区的大小?

var buffer = new Buffer(10);

我认为 Buffer 个实例很可能使用 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,看起来确实如此。类型化数组或低级数组是固定大小的、创建时分配的结构。


旁注:new Buffer(size) 已弃用;请改用 Buffer.alloc

来自 Node.js 文档:

Instances of the Buffer class are similar to arrays of integers but correspond to fixed-sized, raw memory allocations outside the V8 heap. The size of the Buffer is established when it is created and cannot be resized.

由于数组本身需要在初始化时指定其大小,因此 Buffer 也类似。