|
| 1 | +package com.netflix.spectator.atlas; |
| 2 | + |
| 3 | +import com.fasterxml.jackson.core.JsonFactory; |
| 4 | +import com.fasterxml.jackson.core.JsonGenerator; |
| 5 | +import com.fasterxml.jackson.core.JsonParser; |
| 6 | +import com.fasterxml.jackson.core.JsonToken; |
| 7 | +import com.fasterxml.jackson.dataformat.smile.SmileFactory; |
| 8 | +import org.openjdk.jmh.annotations.Benchmark; |
| 9 | +import org.openjdk.jmh.annotations.Scope; |
| 10 | +import org.openjdk.jmh.annotations.Setup; |
| 11 | +import org.openjdk.jmh.annotations.State; |
| 12 | +import org.openjdk.jmh.infra.Blackhole; |
| 13 | + |
| 14 | +import java.io.ByteArrayOutputStream; |
| 15 | +import java.util.Random; |
| 16 | + |
| 17 | +@State(Scope.Thread) |
| 18 | +public class DecodeShortAsciiValues { |
| 19 | + |
| 20 | + private static int N = 100; |
| 21 | + |
| 22 | + private JsonFactory factory; |
| 23 | + private byte[] inputData; |
| 24 | + |
| 25 | + private static String randomShortAsciiString() { |
| 26 | + Random r = new Random(); |
| 27 | + final int length = r.nextInt(64); |
| 28 | + final char[] buf = new char[length]; |
| 29 | + for (int i = 0; i < length; ++i) { |
| 30 | + buf[i] = (char) (r.nextInt('~' - ' ') + ' '); |
| 31 | + } |
| 32 | + return new String(buf); |
| 33 | + } |
| 34 | + |
| 35 | + @Setup |
| 36 | + public void setup() throws Exception { |
| 37 | + factory = new SmileFactory(); |
| 38 | + |
| 39 | + ByteArrayOutputStream baos = new ByteArrayOutputStream(); |
| 40 | + try (JsonGenerator gen = factory.createGenerator(baos)) { |
| 41 | + gen.writeStartArray(); |
| 42 | + for (int i = 0; i < N; ++i) { |
| 43 | + gen.writeString(randomShortAsciiString()); |
| 44 | + } |
| 45 | + gen.writeEndArray(); |
| 46 | + } |
| 47 | + inputData = baos.toByteArray(); |
| 48 | + } |
| 49 | + |
| 50 | + @Benchmark |
| 51 | + public void parse(Blackhole bh) throws Exception { |
| 52 | + String[] strings = new String[N]; |
| 53 | + try (JsonParser parser = factory.createParser(inputData)) { |
| 54 | + parser.nextToken(); |
| 55 | + int i = 0; |
| 56 | + while (parser.nextToken() != JsonToken.END_ARRAY) { |
| 57 | + strings[i++] = parser.getText(); |
| 58 | + } |
| 59 | + } |
| 60 | + bh.consume(strings); |
| 61 | + } |
| 62 | + |
| 63 | + public static void main(String[] args) { |
| 64 | + System.out.println(randomShortAsciiString()); |
| 65 | + } |
| 66 | +} |
0 commit comments