Skip to content

Commit 04b9f85

Browse files
authored
Enhance buffer handling to reduce direct list access. (#1675)
JAVA-5846 --------- Co-authored-by: Maxim Katcharov <[email protected]>
1 parent 943f60e commit 04b9f85

File tree

1 file changed

+14
-4
lines changed

1 file changed

+14
-4
lines changed

driver-core/src/main/com/mongodb/internal/connection/ByteBufferBsonOutput.java

+14-4
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ public class ByteBufferBsonOutput extends OutputBuffer {
4343
private int curBufferIndex = 0;
4444
private int position = 0;
4545
private boolean closed;
46+
private ByteBuf currentByteBuffer;
4647

4748
/**
4849
* Construct an instance that uses the given buffer provider to allocate byte buffers as needs as it grows.
@@ -169,13 +170,16 @@ public void writeByte(final int value) {
169170
}
170171

171172
private ByteBuf getCurrentByteBuffer() {
172-
ByteBuf curByteBuffer = getByteBufferAtIndex(curBufferIndex);
173-
if (curByteBuffer.hasRemaining()) {
174-
return curByteBuffer;
173+
if (currentByteBuffer == null) {
174+
currentByteBuffer = getByteBufferAtIndex(curBufferIndex);
175+
}
176+
if (currentByteBuffer.hasRemaining()) {
177+
return currentByteBuffer;
175178
}
176179

177180
curBufferIndex++;
178-
return getByteBufferAtIndex(curBufferIndex);
181+
currentByteBuffer = getByteBufferAtIndex(curBufferIndex);
182+
return currentByteBuffer;
179183
}
180184

181185
private ByteBuf getByteBufferAtIndex(final int index) {
@@ -259,6 +263,10 @@ public void truncateToPosition(final int newPosition) {
259263

260264
bufferList.get(bufferPositionPair.bufferIndex).position(bufferPositionPair.position);
261265

266+
if (bufferPositionPair.bufferIndex + 1 < bufferList.size()) {
267+
currentByteBuffer = null;
268+
}
269+
262270
while (bufferList.size() > bufferPositionPair.bufferIndex + 1) {
263271
ByteBuf buffer = bufferList.remove(bufferList.size() - 1);
264272
buffer.release();
@@ -286,6 +294,7 @@ public void close() {
286294
for (final ByteBuf cur : bufferList) {
287295
cur.release();
288296
}
297+
currentByteBuffer = null;
289298
bufferList.clear();
290299
closed = true;
291300
}
@@ -325,6 +334,7 @@ private void merge(final ByteBufferBsonOutput branch) {
325334
bufferList.addAll(branch.bufferList);
326335
curBufferIndex += branch.curBufferIndex + 1;
327336
position += branch.position;
337+
currentByteBuffer = null;
328338
}
329339

330340
public static final class Branch extends ByteBufferBsonOutput {

0 commit comments

Comments
 (0)