Performance: Buffer allocation and encoding
This concept affects how fast Node.js allocates memory and processes string data, impacting server response time and throughput.
Jump into concepts and practice - no test required
const buf = Buffer.from('some string data', 'utf8');
const buf = Buffer.allocUnsafe(1000); buf.write('some string data', 0, 'utf8');
| Pattern | Memory Usage | CPU Usage | Garbage Collection Impact | Verdict |
|---|---|---|---|---|
| Buffer.allocUnsafe + manual write | Medium (uninitialized memory) | Medium (manual write CPU) | Higher (possible memory leaks) | [!] OK |
| Buffer.from with encoding | Low (exact size) | Low (single step encoding) | Lower (less GC pressure) | [OK] Good |
Buffer.alloc(5) do in Node.js?Buffer.alloc(size) creates a buffer of the given size and fills it with zeros for safety.Buffer.alloc(5) creates a buffer of length 5 filled with zeros.'hello' using UTF-8 encoding?Buffer.from() creates a buffer from a string with encoding.Buffer.from('hello', 'utf8') is correct syntax; Buffer.alloc does not accept string input, and Buffer.create does not exist. new Buffer() is deprecated.const buf = Buffer.from('abc', 'utf8');
console.log(buf.length);buf.length is 3.const buf = Buffer.alloc(5, 'abc'); console.log(buf.toString());
Buffer.alloc(size, fill) accepts a size and a fill value. The fill can be a string, which repeats to fill the buffer.toString() converts buffer back to string.'café' and then convert it back to a string. Which encoding should you use to preserve the accented character correctly?'utf8' ensures the accented character is preserved when converting to and from buffer.