Prem
Prem

Reputation: 5987

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);

Upvotes: 0

Views: 130

Answers (3)

Muhammad Azam
Muhammad Azam

Reputation: 254

When you create a buffer in a programming language, you are essentially setting aside a specific amount of memory to store data. This memory allocation is necessary for several reasons:

  • Reserved Space
  • Contiguous Memory
  • Preventing Overflows
  • Dynamic Size
  • Proper Initialization
  • Resource Management

Upvotes: 0

rootExplorr
rootExplorr

Reputation: 575

From Node.js documentation :

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.

Since arrays themselves need that their size be specified at initialization hence similarly for Buffer.

Upvotes: 2

T.J. Crowder
T.J. Crowder

Reputation: 1074485

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.

Upvotes: 2

Related Questions