From 2f952fe310a5977743a0404173162e6ebb81a9b8 Mon Sep 17 00:00:00 2001 From: Chad Kimes <1936066+chkimes@users.noreply.github.com> Date: Wed, 13 Jul 2022 10:19:53 -0400 Subject: [PATCH 1/2] Use Buffer.allocUnsafe to reduce allocations --- lib/connection.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/connection.js b/lib/connection.js index 22a73332..10acf607 100644 --- a/lib/connection.js +++ b/lib/connection.js @@ -560,7 +560,7 @@ C.sendMessage = function(channel, var allLen = methodHeaderLen + bodyLen; if (allLen < SINGLE_CHUNK_THRESHOLD) { - var all = Buffer.alloc(allLen); + var all = Buffer.allocUnsafe(allLen); var offset = mframe.copy(all, 0); offset += pframe.copy(all, offset); @@ -570,7 +570,7 @@ C.sendMessage = function(channel, } else { if (methodHeaderLen < SINGLE_CHUNK_THRESHOLD) { - var both = Buffer.alloc(methodHeaderLen); + var both = Buffer.allocUnsafe(methodHeaderLen); var offset = mframe.copy(both, 0); pframe.copy(both, offset); buffer.write(both); From 9da3c9b7017b074a2cd287cee106cdac6df7c1d3 Mon Sep 17 00:00:00 2001 From: Chad Kimes <1936066+chkimes@users.noreply.github.com> Date: Thu, 4 Aug 2022 13:49:30 -0400 Subject: [PATCH 2/2] Update connection.js --- lib/connection.js | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/lib/connection.js b/lib/connection.js index 10acf607..19cbcaa8 100644 --- a/lib/connection.js +++ b/lib/connection.js @@ -560,6 +560,9 @@ C.sendMessage = function(channel, var allLen = methodHeaderLen + bodyLen; if (allLen < SINGLE_CHUNK_THRESHOLD) { + // Use `allocUnsafe` to avoid excessive allocations and CPU usage + // from zeroing. The returned Buffer is not zeroed and so must be + // completely filled to be used safely. var all = Buffer.allocUnsafe(allLen); var offset = mframe.copy(all, 0); offset += pframe.copy(all, offset); @@ -570,6 +573,9 @@ C.sendMessage = function(channel, } else { if (methodHeaderLen < SINGLE_CHUNK_THRESHOLD) { + // Use `allocUnsafe` to avoid excessive allocations and CPU usage + // from zeroing. The returned Buffer is not zeroed and so must be + // completely filled to be used safely. var both = Buffer.allocUnsafe(methodHeaderLen); var offset = mframe.copy(both, 0); pframe.copy(both, offset);