View Javadoc
1   /*
2    * Copyright 2026 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   https://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  package io.netty.buffer;
17  
18  import io.netty.microbench.util.AbstractMicrobenchmark;
19  import org.openjdk.jmh.annotations.Benchmark;
20  import org.openjdk.jmh.annotations.BenchmarkMode;
21  import org.openjdk.jmh.annotations.Fork;
22  import org.openjdk.jmh.annotations.Measurement;
23  import org.openjdk.jmh.annotations.Mode;
24  import org.openjdk.jmh.annotations.OutputTimeUnit;
25  import org.openjdk.jmh.annotations.Setup;
26  import org.openjdk.jmh.annotations.TearDown;
27  import org.openjdk.jmh.annotations.Warmup;
28  
29  import java.util.concurrent.TimeUnit;
30  
31  @Warmup(iterations = 5)
32  @Measurement(iterations = 5)
33  @BenchmarkMode(Mode.AverageTime)
34  @OutputTimeUnit(TimeUnit.NANOSECONDS)
35  public class VarHandleAccessBenchmark extends AbstractMicrobenchmark {
36  
37      private ByteBuf unsafeDirect;
38      private ByteBuf unsafeHeap;
39  
40      @Setup
41      public void setup() {
42          unsafeDirect = new UnpooledUnsafeDirectByteBuf(ByteBufAllocator.DEFAULT, 8, 8);
43          unsafeHeap = new UnpooledUnsafeHeapByteBuf(ByteBufAllocator.DEFAULT, 8, 8);
44          unsafeDirect.setLong(0, 1L);
45          unsafeHeap.setLong(0, 1L);
46      }
47  
48      @TearDown
49      public void tearDown() {
50          unsafeDirect.release();
51          unsafeHeap.release();
52      }
53  
54      // UNALIGNED = false: should use VarHandle for multi-byte access
55      @Benchmark
56      @Fork(value = 1, jvmArgsAppend = "-Dio.netty.unalignedAccess=false")
57      public long getLongDirectFalse() {
58          return unsafeDirect.getLong(0);
59      }
60  
61      @Benchmark
62      @Fork(value = 1, jvmArgsAppend = "-Dio.netty.unalignedAccess=false")
63      public long getLongHeapFalse() {
64          return unsafeHeap.getLong(0);
65      }
66  }