Skip to content

Commit fe796fc

Browse files
normanmaurertrustin
authored andcommitted
Provide helper methods in ByteBufUtil to write UTF-8/ASCII CharSequences. Related to [netty#909]
Motivation: We expose no methods in ByteBuf to directly write a CharSequence into it. This leads to have the user either convert the CharSequence first to a byte array or use CharsetEncoder. Both cases have some overheads and we can do a lot better for well known Charsets like UTF-8 and ASCII. Modifications: Add ByteBufUtil.writeAscii(...) and ByteBufUtil.writeUtf8(...) which can do the task in an optimized way. This is especially true if the passed in ByteBuf extends AbstractByteBuf which is true for all of our implementations which not wrap another ByteBuf. Result: Writing an ASCII and UTF-8 CharSequence into a AbstractByteBuf is a lot faster then what the user could do by himself as we can make use of some package private methods and so eliminate reference and range checks. When the Charseq is not ASCII or UTF-8 we can still do a very good job and are on par in most of the cases with what the user would do. The following benchmark shows the improvements: Result: 2456866.966 ?(99.9%) 59066.370 ops/s [Average] Statistics: (min, avg, max) = (2297025.189, 2456866.966, 2586003.225), stdev = 78851.914 Confidence interval (99.9%): [2397800.596, 2515933.336] Benchmark Mode Samples Score Score error Units i.n.m.b.ByteBufUtilBenchmark.writeAscii thrpt 50 9398165.238 131503.098 ops/s i.n.m.b.ByteBufUtilBenchmark.writeAsciiString thrpt 50 9695177.968 176684.821 ops/s i.n.m.b.ByteBufUtilBenchmark.writeAsciiStringViaArray thrpt 50 4788597.415 83181.549 ops/s i.n.m.b.ByteBufUtilBenchmark.writeAsciiStringViaArrayWrapped thrpt 50 4722297.435 98984.491 ops/s i.n.m.b.ByteBufUtilBenchmark.writeAsciiStringWrapped thrpt 50 4028689.762 66192.505 ops/s i.n.m.b.ByteBufUtilBenchmark.writeAsciiViaArray thrpt 50 3234841.565 91308.009 ops/s i.n.m.b.ByteBufUtilBenchmark.writeAsciiViaArrayWrapped thrpt 50 3311387.474 39018.933 ops/s i.n.m.b.ByteBufUtilBenchmark.writeAsciiWrapped thrpt 50 3379764.250 66735.415 ops/s i.n.m.b.ByteBufUtilBenchmark.writeUtf8 thrpt 50 5671116.821 101760.081 ops/s i.n.m.b.ByteBufUtilBenchmark.writeUtf8String thrpt 50 5682733.440 111874.084 ops/s i.n.m.b.ByteBufUtilBenchmark.writeUtf8StringViaArray thrpt 50 3564548.995 55709.512 ops/s i.n.m.b.ByteBufUtilBenchmark.writeUtf8StringViaArrayWrapped thrpt 50 3621053.671 47632.820 ops/s i.n.m.b.ByteBufUtilBenchmark.writeUtf8StringWrapped thrpt 50 2634029.071 52304.876 ops/s i.n.m.b.ByteBufUtilBenchmark.writeUtf8ViaArray thrpt 50 3397049.332 57784.119 ops/s i.n.m.b.ByteBufUtilBenchmark.writeUtf8ViaArrayWrapped thrpt 50 3318685.262 35869.562 ops/s i.n.m.b.ByteBufUtilBenchmark.writeUtf8Wrapped thrpt 50 2473791.249 46423.114 ops/s Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1,387.417 sec - in io.netty.microbench.buffer.ByteBufUtilBenchmark Results : Tests run: 1, Failures: 0, Errors: 0, Skipped: 0 Results : Tests run: 1, Failures: 0, Errors: 0, Skipped: 0 The *ViaArray* benchmarks are basically doing a toString().getBytes(Charset) which the others are using ByteBufUtil.write*(...).
1 parent cf6eb70 commit fe796fc

3 files changed

Lines changed: 299 additions & 0 deletions

File tree

‎buffer/src/main/java/io/netty/buffer/ByteBufUtil.java‎

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -370,6 +370,92 @@ private static int lastIndexOf(ByteBuf buffer, int fromIndex, int toIndex, byte
370370
return -1;
371371
}
372372

373+
/**
374+
* Encode a {@link CharSequence} in <a href="http://en.wikipedia.org/wiki/UTF-8">UTF-8</a> and write
375+
* it to a {@link ByteBuf}.
376+
*
377+
* This method returns the actual number of bytes written.
378+
*/
379+
public static int writeUtf8(ByteBuf buf, CharSequence seq) {
380+
if (buf == null) {
381+
throw new NullPointerException("buf");
382+
}
383+
if (seq == null) {
384+
throw new NullPointerException("seq");
385+
}
386+
// UTF-8 uses max. 3 bytes per char, so calculate the worst case.
387+
final int len = seq.length();
388+
final int maxSize = len * 3;
389+
buf.ensureWritable(maxSize);
390+
if (buf instanceof AbstractByteBuf) {
391+
// Fast-Path
392+
AbstractByteBuf buffer = (AbstractByteBuf) buf;
393+
int oldWriterIndex = buffer.writerIndex;
394+
int writerIndex = oldWriterIndex;
395+
396+
// We can use the _set methods as these not need to do any index checks and reference checks.
397+
// This is possible as we called ensureWritable(...) before.
398+
for (int i = 0; i < len; i++) {
399+
char c = seq.charAt(i);
400+
if (c < 0x80) {
401+
buffer._setByte(writerIndex++, (byte) c);
402+
} else if (c < 0x800) {
403+
buffer._setByte(writerIndex++, (byte) (0xc0 | (c >> 6)));
404+
buffer._setByte(writerIndex++, (byte) (0x80 | (c & 0x3f)));
405+
} else {
406+
buffer._setByte(writerIndex++, (byte) (0xe0 | (c >> 12)));
407+
buffer._setByte(writerIndex++, (byte) (0x80 | ((c >> 6) & 0x3f)));
408+
buffer._setByte(writerIndex++, (byte) (0x80 | (c & 0x3f)));
409+
}
410+
}
411+
// update the writerIndex without any extra checks for performance reasons
412+
buffer.writerIndex = writerIndex;
413+
return writerIndex - oldWriterIndex;
414+
} else {
415+
// Maybe we could also check if we can unwrap() to access the wrapped buffer which
416+
// may be an AbstractByteBuf. But this may be overkill so let us keep it simple for now.
417+
byte[] bytes = seq.toString().getBytes(CharsetUtil.UTF_8);
418+
buf.writeBytes(bytes);
419+
return bytes.length;
420+
}
421+
}
422+
423+
/**
424+
* Encode a {@link CharSequence} in <a href="http://en.wikipedia.org/wiki/ASCII">ASCII</a> and write it
425+
* to a {@link ByteBuf}.
426+
*
427+
* This method returns the actual number of bytes written.
428+
*/
429+
public static int writeAscii(ByteBuf buf, CharSequence seq) {
430+
if (buf == null) {
431+
throw new NullPointerException("buf");
432+
}
433+
if (seq == null) {
434+
throw new NullPointerException("seq");
435+
}
436+
// ASCII uses 1 byte per char
437+
final int len = seq.length();
438+
buf.ensureWritable(len);
439+
if (buf instanceof AbstractByteBuf) {
440+
// Fast-Path
441+
AbstractByteBuf buffer = (AbstractByteBuf) buf;
442+
int writerIndex = buffer.writerIndex;
443+
444+
// We can use the _set methods as these not need to do any index checks and reference checks.
445+
// This is possible as we called ensureWritable(...) before.
446+
for (int i = 0; i < len; i++) {
447+
buffer._setByte(writerIndex++, (byte) seq.charAt(i));
448+
}
449+
// update the writerIndex without any extra checks for performance reasons
450+
buffer.writerIndex = writerIndex;
451+
} else {
452+
// Maybe we could also check if we can unwrap() to access the wrapped buffer which
453+
// may be an AbstractByteBuf. But this may be overkill so let us keep it simple for now.
454+
buf.writeBytes(seq.toString().getBytes(CharsetUtil.US_ASCII));
455+
}
456+
return len;
457+
}
458+
373459
/**
374460
* Encode the given {@link CharBuffer} using the given {@link Charset} into a new {@link ByteBuf} which
375461
* is allocated via the {@link ByteBufAllocator}.
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/*
2+
* Copyright 2014 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+
* http://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.util.CharsetUtil;
19+
import io.netty.util.ReferenceCountUtil;
20+
import org.junit.Assert;
21+
import org.junit.Test;
22+
23+
public class ByteBufUtilTest {
24+
25+
@Test
26+
public void testWriteUsAscii() {
27+
String usAscii = "NettyRocks";
28+
ByteBuf buf = ReferenceCountUtil.releaseLater(Unpooled.buffer(16));
29+
buf.writeBytes(usAscii.getBytes(CharsetUtil.US_ASCII));
30+
ByteBuf buf2 = ReferenceCountUtil.releaseLater(Unpooled.buffer(16));
31+
ByteBufUtil.writeAscii(buf2, usAscii);
32+
33+
Assert.assertEquals(buf, buf2);
34+
}
35+
36+
@Test
37+
public void testWriteUtf8() {
38+
String usAscii = "Some UTF-8 like äÄ∏ŒŒ";
39+
ByteBuf buf = ReferenceCountUtil.releaseLater(Unpooled.buffer(16));
40+
buf.writeBytes(usAscii.getBytes(CharsetUtil.UTF_8));
41+
ByteBuf buf2 = ReferenceCountUtil.releaseLater(Unpooled.buffer(16));
42+
ByteBufUtil.writeUtf8(buf2, usAscii);
43+
44+
Assert.assertEquals(buf, buf2);
45+
}
46+
}
Lines changed: 167 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,167 @@
1+
/*
2+
* Copyright 2014 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+
* http://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.microbench.buffer;
17+
18+
import io.netty.buffer.ByteBuf;
19+
import io.netty.buffer.ByteBufUtil;
20+
import io.netty.buffer.Unpooled;
21+
import io.netty.microbench.util.AbstractMicrobenchmark;
22+
import io.netty.util.CharsetUtil;
23+
import org.openjdk.jmh.annotations.Benchmark;
24+
import org.openjdk.jmh.annotations.Measurement;
25+
import org.openjdk.jmh.annotations.Scope;
26+
import org.openjdk.jmh.annotations.Setup;
27+
import org.openjdk.jmh.annotations.State;
28+
import org.openjdk.jmh.annotations.TearDown;
29+
import org.openjdk.jmh.annotations.Warmup;
30+
31+
32+
@State(Scope.Benchmark)
33+
@Warmup(iterations = 10)
34+
@Measurement(iterations = 25)
35+
public class ByteBufUtilBenchmark extends AbstractMicrobenchmark {
36+
private ByteBuf buffer;
37+
private ByteBuf wrapped;
38+
39+
private StringBuilder asciiSequence;
40+
private String ascii;
41+
42+
private StringBuilder utf8Sequence;
43+
private String utf8;
44+
45+
@Setup
46+
public void setup() {
47+
// Use buffer sizes that will also allow to write UTF-8 without grow the buffer
48+
buffer = Unpooled.directBuffer(512);
49+
wrapped = Unpooled.unreleasableBuffer(Unpooled.directBuffer(512));
50+
asciiSequence = new StringBuilder(128);
51+
for (int i = 0; i < 128; i++) {
52+
asciiSequence.append('a');
53+
}
54+
ascii = asciiSequence.toString();
55+
56+
// Generate some mixed UTF-8 String for benchmark
57+
utf8Sequence = new StringBuilder(128);
58+
char[] chars = "Some UTF-8 like äÄ∏ŒŒ".toCharArray();
59+
for (int i = 0; i < 128; i++) {
60+
utf8Sequence.append(chars[i % chars.length]);
61+
}
62+
utf8 = utf8Sequence.toString();
63+
asciiSequence = utf8Sequence;
64+
}
65+
66+
@TearDown
67+
public void tearDown() {
68+
buffer.release();
69+
wrapped.release();
70+
}
71+
72+
@Benchmark
73+
public void writeAsciiStringViaArray() {
74+
buffer.resetWriterIndex();
75+
buffer.writeBytes(ascii.getBytes(CharsetUtil.US_ASCII));
76+
}
77+
78+
@Benchmark
79+
public void writeAsciiStringViaArrayWrapped() {
80+
wrapped.resetWriterIndex();
81+
wrapped.writeBytes(ascii.getBytes(CharsetUtil.US_ASCII));
82+
}
83+
84+
@Benchmark
85+
public void writeAsciiString() {
86+
buffer.resetWriterIndex();
87+
ByteBufUtil.writeAscii(buffer, ascii);
88+
}
89+
90+
@Benchmark
91+
public void writeAsciiStringWrapped() {
92+
wrapped.resetWriterIndex();
93+
ByteBufUtil.writeAscii(wrapped, ascii);
94+
}
95+
96+
@Benchmark
97+
public void writeAsciiViaArray() {
98+
buffer.resetWriterIndex();
99+
buffer.writeBytes(asciiSequence.toString().getBytes(CharsetUtil.US_ASCII));
100+
}
101+
102+
@Benchmark
103+
public void writeAsciiViaArrayWrapped() {
104+
wrapped.resetWriterIndex();
105+
wrapped.writeBytes(asciiSequence.toString().getBytes(CharsetUtil.US_ASCII));
106+
}
107+
108+
@Benchmark
109+
public void writeAscii() {
110+
buffer.resetWriterIndex();
111+
ByteBufUtil.writeAscii(buffer, asciiSequence);
112+
}
113+
114+
@Benchmark
115+
public void writeAsciiWrapped() {
116+
wrapped.resetWriterIndex();
117+
ByteBufUtil.writeAscii(wrapped, asciiSequence);
118+
}
119+
120+
@Benchmark
121+
public void writeUtf8StringViaArray() {
122+
buffer.resetWriterIndex();
123+
buffer.writeBytes(utf8.getBytes(CharsetUtil.US_ASCII));
124+
}
125+
126+
@Benchmark
127+
public void writeUtf8StringViaArrayWrapped() {
128+
wrapped.resetWriterIndex();
129+
wrapped.writeBytes(utf8.getBytes(CharsetUtil.US_ASCII));
130+
}
131+
132+
@Benchmark
133+
public void writeUtf8String() {
134+
buffer.resetWriterIndex();
135+
ByteBufUtil.writeUtf8(buffer, utf8);
136+
}
137+
138+
@Benchmark
139+
public void writeUtf8StringWrapped() {
140+
wrapped.resetWriterIndex();
141+
ByteBufUtil.writeUtf8(wrapped, utf8);
142+
}
143+
144+
@Benchmark
145+
public void writeUtf8ViaArray() {
146+
buffer.resetWriterIndex();
147+
buffer.writeBytes(utf8Sequence.toString().getBytes(CharsetUtil.US_ASCII));
148+
}
149+
150+
@Benchmark
151+
public void writeUtf8ViaArrayWrapped() {
152+
wrapped.resetWriterIndex();
153+
wrapped.writeBytes(utf8Sequence.toString().getBytes(CharsetUtil.US_ASCII));
154+
}
155+
156+
@Benchmark
157+
public void writeUtf8() {
158+
buffer.resetWriterIndex();
159+
ByteBufUtil.writeUtf8(buffer, utf8Sequence);
160+
}
161+
162+
@Benchmark
163+
public void writeUtf8Wrapped() {
164+
wrapped.resetWriterIndex();
165+
ByteBufUtil.writeUtf8(wrapped, utf8Sequence);
166+
}
167+
}

0 commit comments

Comments
 (0)