Skip to content

Commit cc3872d

Browse files
authored
Reduce composite references at network level (#36400)
Creating `CompositeBytesReference` has more overhead than a single `ByteBufferReference`. Many of our messages will be contained to a single `ByteBuffer`. This commit avoids creating composite instances when there is 0 or 1 underlying `ByteBuffers`.
1 parent b5b6e37 commit cc3872d

File tree

2 files changed

+15
-8
lines changed

2 files changed

+15
-8
lines changed

server/src/main/java/org/elasticsearch/common/bytes/ByteBufferReference.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,8 +25,8 @@
2525

2626
/**
2727
* This is a {@link BytesReference} backed by a {@link ByteBuffer}. The byte buffer can either be a heap or
28-
* direct byte buffer. The reference is composed of the space between the {@link ByteBuffer#position} and
29-
* {@link ByteBuffer#limit} at construction time. If the position or limit of the underlying byte buffer is
28+
* direct byte buffer. The reference is composed of the space between the {@link ByteBuffer#position()} and
29+
* {@link ByteBuffer#limit()} at construction time. If the position or limit of the underlying byte buffer is
3030
* changed, those changes will not be reflected in this reference. However, modifying the limit or position
3131
* of the underlying byte buffer is not recommended as those can be used during {@link ByteBuffer#get()}
3232
* bounds checks. Use {@link ByteBuffer#duplicate()} at creation time if you plan on modifying the markers of

server/src/main/java/org/elasticsearch/common/bytes/BytesReference.java

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -195,17 +195,24 @@ public static ByteBuffer[] toByteBuffers(BytesReference reference) {
195195
* Returns BytesReference composed of the provided ByteBuffers.
196196
*/
197197
public static BytesReference fromByteBuffers(ByteBuffer[] buffers) {
198-
ByteBufferReference[] references = new ByteBufferReference[buffers.length];
199-
for (int i = 0; i < references.length; ++i) {
200-
references[i] = new ByteBufferReference(buffers[i]);
201-
}
198+
int bufferCount = buffers.length;
199+
if (bufferCount == 0) {
200+
return BytesArray.EMPTY;
201+
} else if (bufferCount == 1) {
202+
return new ByteBufferReference(buffers[0]);
203+
} else {
204+
ByteBufferReference[] references = new ByteBufferReference[bufferCount];
205+
for (int i = 0; i < bufferCount; ++i) {
206+
references[i] = new ByteBufferReference(buffers[i]);
207+
}
202208

203-
return new CompositeBytesReference(references);
209+
return new CompositeBytesReference(references);
210+
}
204211
}
205212

206213
@Override
207214
public int compareTo(final BytesReference other) {
208-
return compareIterators(this, other, (a, b) -> a.compareTo(b));
215+
return compareIterators(this, other, BytesRef::compareTo);
209216
}
210217

211218
/**

0 commit comments

Comments
 (0)