Skip to content

Instantly share code, notes, and snippets.

@danielshaya
Created September 21, 2015 15:34
Show Gist options
  • Save danielshaya/070355a2adf176ec063b to your computer and use it in GitHub Desktop.
Save danielshaya/070355a2adf176ec063b to your computer and use it in GitHub Desktop.
Comparing Chronicle-Bytes with ByteBuffer
package test;
import net.openhft.chronicle.bytes.Bytes;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.infra.Blackhole;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import org.openjdk.jmh.runner.options.TimeValue;
import java.lang.reflect.InvocationTargetException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;
/**
* Results:
* Benchmark Mode Cnt Score Error Units
* BytesPerfTest.testByteBuffer sample 451723 302.436 ± 8.260 ns/op
* BytesPerfTest.testChronicleBytes sample 418022 179.129 ± 1.307 ns/op
*/
@State(Scope.Thread)
public class BytesPerfTest {
Blackhole bh = new Blackhole();
StringBuilder sb = new StringBuilder();
Bytes bytes = Bytes.elasticByteBuffer();
ByteBuffer buffer = ByteBuffer.allocateDirect(50);
public BytesPerfTest() {
sb.append("Hello World");
}
public static void main(String[] args) throws InvocationTargetException, IllegalAccessException, RunnerException {
Options opt = new OptionsBuilder()
.include(BytesPerfTest.class.getSimpleName())
.warmupIterations(3)
.forks(1)
.measurementIterations(3)
.mode(Mode.SampleTime)
.measurementTime(TimeValue.seconds(10))
.timeUnit(TimeUnit.NANOSECONDS)
.build();
new Runner(opt).run();
}
@Benchmark
public void testChronicleBytes() {
bytes.clearAndPad(8);
bytes.appendUtf8(sb);
bytes.prewriteByte((byte) ' ');
bytes.prepend(sb.length());
//consumes the separator
int length = (int)bytes.parseLong();
bytes.parseUTF(sb, length);
bh.consume(sb);
}
@Benchmark
public void testByteBuffer() {
buffer.clear();
byte[] bytes1 = sb.toString().getBytes(StandardCharsets.UTF_8);
int len3 = bytes1.length;
buffer.put(Integer.toString(len3).getBytes());
buffer.put((byte) ' ');
buffer.put(bytes1);
buffer.flip();
int number = 0;
byte b = buffer.get();
while(b >= '0' && b<='9'){
number *= 10;
number += b - '0';
b = buffer.get();
}
byte[] dst = new byte[number];
buffer.get(dst);
String s = new String(dst, StandardCharsets.UTF_8);
bh.consume(s);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment