Merge pull request #4235 from Tyriar/opt_server_buffer

Avoid GC pressure from server data buffer
This commit is contained in:
Daniel Imms
2022-10-27 22:41:07 -07:00
committed by GitHub
+13 -10
View File
@@ -111,27 +111,30 @@ function startServer() {
} }
// binary message buffering // binary message buffering
function bufferUtf8(socket, timeout, maxSize) { function bufferUtf8(socket, timeout, maxSize) {
let buffer = []; const dataBuffer = new Uint8Array(maxSize);
let sender = null; let sender = null;
let length = 0; let length = 0;
return (data) => { return (data) => {
buffer.push(data); function flush() {
length += data.length; socket.send(Buffer.from(dataBuffer.buffer, 0, length));
if (length > maxSize || userInput) {
userInput = false;
socket.send(Buffer.concat(buffer, length));
buffer = [];
length = 0; length = 0;
if (sender) { if (sender) {
clearTimeout(sender); clearTimeout(sender);
sender = null; sender = null;
} }
}
if (length + data.length > maxSize) {
flush();
}
dataBuffer.set(data, length);
length += data.length;
if (length > maxSize || userInput) {
userInput = false;
flush();
} else if (!sender) { } else if (!sender) {
sender = setTimeout(() => { sender = setTimeout(() => {
socket.send(Buffer.concat(buffer, length));
buffer = [];
sender = null; sender = null;
length = 0; flush();
}, timeout); }, timeout);
} }
}; };