Skip to content

Commit 316b119

Browse files
committed
fix: major performance issues with bytea performance brianc#2240
1 parent 13ff0e1 commit 316b119

File tree

1 file changed

+17
-5
lines changed

1 file changed

+17
-5
lines changed

packages/pg-protocol/src/parser.ts

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -96,11 +96,20 @@ export class Parser {
9696
const newLength = this.remainingBufferLength + combinedBufferLength
9797
const newFullLength = newLength + this.remainingBufferOffset
9898
if (newFullLength > this.remainingBuffer.byteLength) {
99-
let newBufferLength = this.remainingBuffer.byteLength * 2
100-
while (newLength >= newBufferLength) {
101-
newBufferLength *= 2
99+
// We can't concat the new buffer with the remaining one
100+
let newBuffer: Buffer
101+
if (newLength <= this.remainingBuffer.byteLength && this.remainingBufferOffset >= this.remainingBufferLength) {
102+
// We can move the relevant part to the beginning of the buffer instead of allocating a new buffer
103+
newBuffer = this.remainingBuffer
104+
} else {
105+
// Allocate a new larger buffer
106+
let newBufferLength = this.remainingBuffer.byteLength * 2
107+
while (newLength >= newBufferLength) {
108+
newBufferLength *= 2
109+
}
110+
newBuffer = Buffer.allocUnsafe(newBufferLength)
102111
}
103-
const newBuffer = Buffer.allocUnsafe(newBufferLength)
112+
// Move the remaining buffer to the new one
104113
this.remainingBuffer.copy(
105114
newBuffer,
106115
0,
@@ -110,6 +119,7 @@ export class Parser {
110119
this.remainingBuffer = newBuffer
111120
this.remainingBufferOffset = 0
112121
}
122+
// Concat the new buffer with the remaining one
113123
buffer.copy(this.remainingBuffer, this.remainingBufferOffset + this.remainingBufferLength)
114124
combinedBuffer = this.remainingBuffer
115125
combinedBufferLength = this.remainingBufferLength = newLength
@@ -134,16 +144,18 @@ export class Parser {
134144
break
135145
}
136146
}
137-
138147
if (offset === fullLength) {
148+
// No more use for the buffer
139149
this.remainingBuffer = emptyBuffer
140150
this.remainingBufferLength = 0
141151
this.remainingBufferOffset = 0
142152
} else {
143153
if (reuseRemainingBuffer) {
154+
// Adjust the cursors of remainingBuffer
144155
this.remainingBufferLength = combinedBufferLength - offset
145156
this.remainingBufferOffset += offset
146157
} else {
158+
// To avoid side effects, copy the remaining part of the new buffer to remainingBuffer
147159
this.remainingBuffer = combinedBuffer.slice(offset)
148160
this.remainingBufferLength = this.remainingBuffer.byteLength
149161
this.remainingBufferOffset = 0

0 commit comments

Comments
 (0)