GeezerVison is showing github.com — Avoid allocating NIO buffer views in AdaptiveByteBuf.setBytes(int, ByteBuf, int, int) by lhotari · Pull Request #17840 · netty/netty
Avoid allocating NIO buffer views in AdaptiveByteBuf.setBytes(int, ByteBuf, int, int)
#17840
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement . We’ll occasionally send you account related emails.
Already on GitHub?
Sign in
to your account
Uh oh!
There was an error while loading. Please reload this page.
Show file tree
Hide file tree
Changes from all commits
Commits
File filter
Filter by extension
.java
(3)
All 1 file type selected
Viewed files
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Diff view
Hide whitespace
Diff view
Hide whitespace
There are no files selected for viewing
Original file line number
Diff line number
Diff line change
Expand Up
@@ -2481,6 +2481,15 @@ public ByteBuf setBytes(int index, byte[] src, int srcIndex, int length) {
@Override
public ByteBuf setBytes(int index, ByteBuf src, int srcIndex, int length) {
if (PlatformDependent.hasUnsafe() && hasMemoryAddress) {
Comment thread
lhotari marked this conversation as resolved.
Resolved
Uh oh!
There was an error while loading. Please reload this page.
// Copies from a source with a memory address or an array without an NIO buffer view of the source,
// which src.nioBuffer(...) below would allocate for each copy from a buffer of another kind, such
// as a slice or a buffer of another allocator. Without Unsafe, a direct buffer can still have a
// memory address (Java 25+), but the copy needs Unsafe; checking hasUnsafe() first lets the JIT
// drop this branch then.
UnsafeByteBufUtil.setBytes(this, _memoryAddress() + index, index, src, srcIndex, length);
return this;
}
checkIndex(index, length);
if (src instanceof AdaptiveByteBuf && PlatformDependent.javaVersion() >= 16) {
AdaptiveByteBuf srcBuf = (AdaptiveByteBuf) src;
Expand Down
Expand Up
@@ -2685,6 +2694,7 @@ protected void deallocate() {
chunk = null;
rootParent = null;
memoryAddress = 0L;
hasMemoryAddress = false;
handle.unguardedRecycle(this);
}
}
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -18,6 +18,9 @@
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
public abstract class AbstractAdaptiveByteBufTest extends AbstractPooledByteBufTest {
private final AdaptiveByteBufAllocator allocator = new AdaptiveByteBufAllocator();
Expand All
@@ -39,4 +42,48 @@ public void testMaxFastWritableBytes() {
@Override
public void testEnsureWritableDoesntGrowTooMuch() {
}
@Test
public void testSetBytesFromBuffersOfOtherKinds() {
final byte[] bytes = new byte[64];
for (int i = 0; i < bytes.length; i++) {
bytes[i] = (byte) (i + 1);
}
ByteBuf pooledDirect = PooledByteBufAllocator.DEFAULT.directBuffer(72).writeZero(8).writeBytes(bytes);
ByteBuf unpooledHeap = Unpooled.buffer(72).writeZero(8).writeBytes(bytes);
ByteBuf adaptive = alloc(72, 72).writeZero(8).writeBytes(bytes);
CompositeByteBuf composite = Unpooled.compositeBuffer().addComponents(true,
Unpooled.directBuffer(32).writeBytes(bytes, 0, 32),
Unpooled.buffer(32).writeBytes(bytes, 32, 32));
ByteBuf wrappedHeap = Unpooled.wrappedBuffer(bytes);
final ByteBuf[] sources = {
pooledDirect.slice(8, 64),
unpooledHeap.slice(8, 64),
adaptive.slice(8, 64),
composite,
wrappedHeap.asReadOnly(),
};
final ByteBuf target = alloc(128, 128);
try {
for (ByteBuf src : sources) {
target.clear().writeZero(128);
target.setBytes(16, src, 4, 40);
for (int i = 0; i < 128; i++) {
byte expected = i >= 16 && i < 56 ? bytes[i - 16 + 4] : 0;
assertEquals(expected, target.getByte(i), "index " + i + " from " + src);
}
assertEquals(0, src.readerIndex());
assertEquals(64, src.writerIndex());
}
assertThrows(IndexOutOfBoundsException.class, () -> target.setBytes(0, sources[0], 40, 40));
assertThrows(IndexOutOfBoundsException.class, () -> target.setBytes(100, sources[0], 0, 40));
} finally {
target.release();
pooledDirect.release();
unpooledHeap.release();
adaptive.release();
composite.release();
wrappedHeap.release();
}
}
}
Original file line number
Diff line number
Diff line change
@@ -0,0 +1,114 @@
/*
* Copyright 2026 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.microbench.buffer;
import io.netty.buffer.AdaptiveByteBufAllocator;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.CompositeByteBuf;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.buffer.Unpooled;
import io.netty.microbench.util.AbstractMicrobenchmark;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.TearDown;
/**
* Copies into a direct buffer of the {@link AdaptiveByteBufAllocator} from sources of different kinds, as
* {@code target.writeBytes(source)} does. Run with {@code -prof gc} to see the allocations per copy.
*
* <p>Unsafe is enabled explicitly, since Netty disables it by default on Java 25+; to compare without it, pass
* {@code -jvmArgsAppend -Dio.netty.noUnsafe=true}.
*/
@Fork(value = 2, jvmArgsAppend = "-Dio.netty.noUnsafe=false")
public class AdaptiveByteBufSetBytesBenchmark extends AbstractMicrobenchmark {
public enum Source {
ADAPTIVE,
ADAPTIVE_SLICE,
POOLED_DIRECT,
POOLED_DIRECT_SLICE,
UNPOOLED_HEAP,
COMPOSITE
}
@Param({
"64",
"1024",
"16384",
})
private int size;
@Param
private Source source;
private final AdaptiveByteBufAllocator adaptiveAllocator = new AdaptiveByteBufAllocator();
private ByteBuf sourceRoot;
private ByteBuf src;
private ByteBuf target;
@Setup
public void setup() {
switch (source) {
case ADAPTIVE:
sourceRoot = adaptiveAllocator.directBuffer(size, size);
src = sourceRoot;
break;
case ADAPTIVE_SLICE:
sourceRoot = adaptiveAllocator.directBuffer(size + 8, size + 8);
src = sourceRoot.slice(8, size);
break;
case POOLED_DIRECT:
sourceRoot = PooledByteBufAllocator.DEFAULT.directBuffer(size, size);
src = sourceRoot;
break;
case POOLED_DIRECT_SLICE:
sourceRoot = PooledByteBufAllocator.DEFAULT.directBuffer(size + 8, size + 8);
src = sourceRoot.slice(8, size);
break;
case UNPOOLED_HEAP:
sourceRoot = Unpooled.buffer(size, size);
src = sourceRoot;
break;
case COMPOSITE:
CompositeByteBuf composite = Unpooled.compositeBuffer();
composite.addComponents(true,
PooledByteBufAllocator.DEFAULT.directBuffer(size / 2).writeZero(size / 2),
PooledByteBufAllocator.DEFAULT.directBuffer(size - size / 2).writeZero(size - size / 2));
sourceRoot = composite;
src = composite;
break;
default:
throw new IllegalArgumentException(String.valueOf(source));
}
for (int i = 0; i < size; i++) {
src.setByte(i, 0xA5);
}
target = adaptiveAllocator.directBuffer(size, size);
}
@Benchmark
public ByteBuf setBytes() {
return target.setBytes(0, src, 0, size);
}
@TearDown
public void tearDown() {
target.release();
sourceRoot.release();
}
}
Loading
Oops, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.