From 672e7c4b66468828d982aae72ee0f22fe3d2ca09 Mon Sep 17 00:00:00 2001 From: Anuraag Agrawal Date: Tue, 14 May 2019 16:42:49 +0900 Subject: [PATCH] Let Java copy arrays which it can sometimes do faster than manual loops. (#2591) --- .../src/main/java/zipkin2/SpanBenchmarks.java | 20 +++++++++++++++++++ zipkin/src/main/java/zipkin2/Span.java | 16 ++++++++++++--- 2 files changed, 33 insertions(+), 3 deletions(-) diff --git a/benchmarks/src/main/java/zipkin2/SpanBenchmarks.java b/benchmarks/src/main/java/zipkin2/SpanBenchmarks.java index a30a1d2333a..182c7aeb120 100644 --- a/benchmarks/src/main/java/zipkin2/SpanBenchmarks.java +++ b/benchmarks/src/main/java/zipkin2/SpanBenchmarks.java @@ -143,6 +143,26 @@ public byte[] deserialize_kryo() { return output.getBuffer(); } + @Benchmark + public String padLeft_1Char() { + return Span.padLeft("1", 16); + } + + @Benchmark + public String padLeft_15Chars() { + return Span.padLeft("123456789012345", 16); + } + + @Benchmark + public String padLeft_17Chars() { + return Span.padLeft("12345678901234567", 32); + } + + @Benchmark + public String padLeft_31Chars() { + return Span.padLeft("1234567890123456789012345678901", 32); + } + // Convenience main entry-point public static void main(String[] args) throws RunnerException { Options opt = new OptionsBuilder() diff --git a/zipkin/src/main/java/zipkin2/Span.java b/zipkin/src/main/java/zipkin2/Span.java index 6ea685d4b1d..8d22bce5e9b 100644 --- a/zipkin/src/main/java/zipkin2/Span.java +++ b/zipkin/src/main/java/zipkin2/Span.java @@ -659,11 +659,21 @@ public static String normalizeTraceId(String traceId) { } } + static final String THIRTY_TWO_ZEROS; + static { + char[] zeros = new char[32]; + Arrays.fill(zeros, '0'); + THIRTY_TWO_ZEROS = new String(zeros); + } + static String padLeft(String id, int desiredLength) { + int length = id.length(); + int numZeros = desiredLength - length; + char[] data = Platform.shortStringBuffer(); - int i = 0, length = id.length(), offset = desiredLength - length; - for (; i < offset; i++) data[i] = '0'; - for (int j = 0; j < length; j++) data[i++] = id.charAt(j); + THIRTY_TWO_ZEROS.getChars(0, numZeros, data, 0); + id.getChars(0, length, data, numZeros); + return new String(data, 0, desiredLength); }