Skip to content

Commit c31205f

Browse files
committed
fix: major performance issues with bytea performance brianc#2240
1 parent 0455504 commit c31205f

File tree

1 file changed

+10
-8
lines changed

1 file changed

+10
-8
lines changed

packages/pg-protocol/src/parser.ts

+10-8
Original file line numberDiff line numberDiff line change
@@ -91,11 +91,12 @@ export class Parser {
9191
let combinedBuffer = buffer
9292
let combinedBufferOffset = 0
9393
let combinedBufferLength = buffer.byteLength
94-
const newRealLength = this.remainingBufferLength + combinedBufferLength
95-
if (this.remainingBufferLength) {
94+
let remainingBufferNotEmpty = this.remainingBufferLength > 0
95+
if (remainingBufferNotEmpty) {
96+
const newRealLength = this.remainingBufferLength + combinedBufferLength
9697
const newLength = newRealLength + this.remainingBufferOffset
9798
if (newLength > this.remainingBuffer.byteLength) {
98-
let newBufferLength = this.remainingBufferLength * 2
99+
let newBufferLength = this.remainingBuffer.byteLength * 2
99100
while (newRealLength >= newBufferLength) {
100101
newBufferLength *= 2
101102
}
@@ -111,11 +112,12 @@ export class Parser {
111112
}
112113
buffer.copy(this.remainingBuffer, this.remainingBufferOffset + this.remainingBufferLength)
113114
combinedBuffer = this.remainingBuffer
114-
combinedBufferLength = newRealLength
115+
combinedBufferLength = this.remainingBufferLength = newRealLength
115116
combinedBufferOffset = this.remainingBufferOffset
116117
}
118+
const realLength = combinedBufferOffset + combinedBufferLength
117119
let offset = combinedBufferOffset
118-
while (offset + HEADER_LENGTH <= combinedBufferLength) {
120+
while (offset + HEADER_LENGTH <= realLength) {
119121
// code is 1 byte long - it identifies the message type
120122
const code = combinedBuffer[offset]
121123

@@ -124,7 +126,7 @@ export class Parser {
124126

125127
const fullMessageLength = CODE_LENGTH + length
126128

127-
if (fullMessageLength + offset <= combinedBufferLength) {
129+
if (fullMessageLength + offset <= realLength) {
128130
const message = this.handlePacket(offset + HEADER_LENGTH, code, length, combinedBuffer)
129131
callback(message)
130132
offset += fullMessageLength
@@ -133,12 +135,12 @@ export class Parser {
133135
}
134136
}
135137

136-
if (offset === combinedBufferLength) {
138+
if (offset === realLength) {
137139
this.remainingBuffer = emptyBuffer
138140
this.remainingBufferLength = 0
139141
this.remainingBufferOffset = 0
140142
} else {
141-
this.remainingBuffer = combinedBuffer
143+
this.remainingBuffer = remainingBufferNotEmpty ? combinedBuffer : combinedBuffer.slice()
142144
this.remainingBufferLength = combinedBufferLength - offset
143145
this.remainingBufferOffset += offset
144146
}

0 commit comments

Comments
 (0)