Performance: Creating buffers
This concept affects memory allocation speed and CPU usage during buffer creation, impacting server response time and throughput.
Jump into concepts and practice - no test required
const buf = Buffer.alloc(1024);const buf = Buffer.allocUnsafe(1024); buf.fill(0);
| Pattern | Memory Allocation | CPU Usage | Event Loop Impact | Verdict |
|---|---|---|---|---|
| Buffer.allocUnsafe + fill | Allocates uninitialized + manual fill | Higher CPU due to fill | Blocks event loop briefly | [X] Bad |
| Buffer.alloc | Allocates zero-filled memory once | Lower CPU usage | Minimal event loop blocking | [OK] Good |
| Repeated Buffer.from(string) | Many allocations | High CPU and GC pressure | Possible event loop delays | [X] Bad |
| Buffer reuse for common data | Single allocation reused | Low CPU and GC | Smooth event loop | [OK] Good |
Buffer.alloc(10) do in Node.js?Buffer.alloc(size) creates a buffer of the given size filled with zeros.Buffer.from(string) creates a buffer from a string.Buffer.alloc expects a size number, new Buffer is deprecated, and Buffer.create does not exist.const buf = Buffer.from('abc');
console.log(buf.length);Buffer.from('abc') creates a buffer with bytes representing 'a', 'b', 'c'.const buf = Buffer.alloc('5');
console.log(buf.length);Buffer.alloc expects a number for size, but '5' is a string.Buffer.from(array) creates a buffer from an array of byte values correctly.buf.toString() converts the buffer bytes to the string 'Hello'.Buffer.alloc([72,101,108,108,111]) is wrong because alloc expects a number. Using Buffer.from('72,101,108,108,111') creates a buffer from the string of numbers, not bytes. Using buf.write([72,101,108,108,111]) is invalid as write doesn't accept arrays directly.