Performance: Buffer to string conversion
This concept affects the speed of converting binary data to readable text, impacting server response time and memory usage.
Jump into concepts and practice - no test required
const str = buffer.toString('utf8'); // convert once and reuse
const str = buffer.toString('utf8'); // called multiple times unnecessarily
| Pattern | CPU Usage | Memory Usage | Latency Impact | Verdict |
|---|---|---|---|---|
| Repeated buffer.toString() calls | High | High | Increased latency | [X] Bad |
| Single buffer.toString() call reused | Low | Low | Minimal latency | [OK] Good |
toString() method do when called on a Node.js Buffer?toString() method converts this raw data into a readable string using a specified encoding, defaulting to UTF-8.buf to a string using ASCII encoding?toString() method takes an optional encoding as a string argument inside parentheses.const buf = Buffer.from('48656c6c6f', 'hex');
console.log(buf.toString());toString() without encoding defaults to UTF-8, decoding bytes to 'Hello'.const buf = Buffer.from('hello');
const str = buf.toString(utf8);
console.log(str);buf containing UTF-8 encoded text. How do you convert only the first 5 bytes to a string?toString() method can take encoding, start, and end byte positions.toString('utf8', 0, 5) specifying encoding and byte range.