1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.buffer;
17
18 import org.openjdk.jmh.annotations.Benchmark;
19 import org.openjdk.jmh.annotations.Measurement;
20 import org.openjdk.jmh.annotations.Param;
21 import org.openjdk.jmh.annotations.Setup;
22 import org.openjdk.jmh.annotations.TearDown;
23 import org.openjdk.jmh.annotations.Warmup;
24
25 import io.netty.microbench.util.AbstractMicrobenchmark;
26
27 import static io.netty.buffer.Unpooled.EMPTY_BUFFER;
28 import static io.netty.buffer.Unpooled.wrappedBuffer;
29
30 import java.util.ArrayList;
31 import java.util.List;
32 import java.util.Random;
33 import java.util.concurrent.TimeUnit;
34
35 @Warmup(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
36 @Measurement(iterations = 10, time = 1, timeUnit = TimeUnit.SECONDS)
37 public class CompositeByteBufRandomAccessBenchmark extends AbstractMicrobenchmark {
38
39 public enum ByteBufType {
40 SMALL_CHUNKS {
41 @Override
42 ByteBuf newBuffer(int length) {
43 return newBufferSmallChunks(length);
44 }
45 },
46 LARGE_CHUNKS {
47 @Override
48 ByteBuf newBuffer(int length) {
49 return newBufferLargeChunks(length);
50 }
51 };
52 abstract ByteBuf newBuffer(int length);
53 }
54
55 @Param({ "64", "10240", "1024000" })
56 public int size;
57
58 @Param
59 public ByteBufType bufferType;
60
61 private ByteBuf buffer;
62 private Random random;
63
64 @Setup
65 public void setup() {
66 buffer = bufferType.newBuffer(size);
67 random = new Random(0L);
68 }
69
70 @TearDown
71 public void teardown() {
72 buffer.release();
73 }
74
75 @Benchmark
76 public long setGetLong() {
77 int i = random.nextInt(size - 8);
78 return buffer.setLong(i, 1).getLong(i);
79 }
80
81 @Benchmark
82 public ByteBuf setLong() {
83 int i = random.nextInt(size - 8);
84 return buffer.setLong(i, 1);
85 }
86
87 private static ByteBuf newBufferSmallChunks(int length) {
88
89 List<ByteBuf> buffers = new ArrayList<ByteBuf>(((length + 1) / 45) * 19);
90 for (int i = 0; i < length + 45; i += 45) {
91 for (int j = 1; j <= 9; j++) {
92 buffers.add(EMPTY_BUFFER);
93 buffers.add(wrappedBuffer(new byte[j]));
94 }
95 buffers.add(EMPTY_BUFFER);
96 }
97
98 ByteBuf buffer = wrappedBuffer(Integer.MAX_VALUE, buffers.toArray(new ByteBuf[0]));
99
100
101 return buffer.capacity(length).writerIndex(0);
102 }
103
104 private static ByteBuf newBufferLargeChunks(int length) {
105
106 List<ByteBuf> buffers = new ArrayList<ByteBuf>((length + 1) / 512);
107 for (int i = 0; i < length + 1536; i += 1536) {
108 buffers.add(wrappedBuffer(new byte[512]));
109 buffers.add(EMPTY_BUFFER);
110 buffers.add(wrappedBuffer(new byte[1024]));
111 }
112
113 ByteBuf buffer = wrappedBuffer(Integer.MAX_VALUE, buffers.toArray(new ByteBuf[0]));
114
115
116 return buffer.capacity(length).writerIndex(0);
117 }
118 }