3 ms·
For the performance footnote... I think the misunderstanding comes from the fact calling .write() on sockets is pretty expensive. Specifically, if you write
by londons_explore 3y ago
For the performance footnote...
I think the misunderstanding comes from the fact calling .write() on sockets is pretty expensive. Specifically, if you write a byte or two, then the OS might send a whole packet out onto the network with just those two bytes.
If you did that for every tiny websocket message, then you would be sending double the number of packets necessary, with matching CPU overhead. Double the chance of network losses causing head of line blocking too.
So... Calling .write() should be done for large buffers and as rarely as possible.
However, in this case, .writeUInt16BE() doesn't send anything onto the network, but presumably the original author has been burned by .write() being expensive before...
- iudqnolq 3y agoI think the author expected that creating a u16 view over a buffer up front and then writing to it would perform better than writing one-off to a single pair as a u16. If they're gonna optimize further I think they may as well go all the way through. This'll be pretty readable in the context of a binary serializer codebase b[2] = value >>> 8; b[3] = value & 0xff;
- withinboredom 3y agoSounds like you've re-invented Nagle's algorithm.