From 2d5eba6de3251481caba4614f79c245f0f29df88 Mon Sep 17 00:00:00 2001 From: hutiefang76 <137664623+hutiefang76@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:48:24 +0800 Subject: [PATCH 1/3] perf: reuse repeated ASCII field names up to 32 bytes --- .../benchmark/LongFieldNameCache.java | 60 ++++++ .../main/resources/data/otlp-metrics.LICENSE | 6 + .../src/main/resources/data/otlp-metrics.json | 140 ++++++++++++++ .../com/alibaba/fastjson2/JSONFactory.java | 2 + .../alibaba/fastjson2/JSONReaderASCII.java | 3 + .../com/alibaba/fastjson2/JSONReaderUTF8.java | 46 +++++ .../fastjson2/JSONFactoryNameCacheTest.java | 176 ++++++++++++++++++ 7 files changed, 433 insertions(+) create mode 100644 benchmark/src/main/java/com/alibaba/fastjson2/benchmark/LongFieldNameCache.java create mode 100644 benchmark/src/main/resources/data/otlp-metrics.LICENSE create mode 100644 benchmark/src/main/resources/data/otlp-metrics.json diff --git a/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/LongFieldNameCache.java b/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/LongFieldNameCache.java new file mode 100644 index 0000000000..4804440f88 --- /dev/null +++ b/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/LongFieldNameCache.java @@ -0,0 +1,60 @@ +package com.alibaba.fastjson2.benchmark; + +import com.alibaba.fastjson2.JSON; +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.Param; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.Setup; +import org.openjdk.jmh.annotations.State; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; + +/** + * Benchmark for long field name caching in fastjson2. + * Compares parsing performance with standard OTLP metrics JSON containing long property names + * (e.g., startTimeUnixNano, aggregationTemporality, exponentialHistogram) versus a modified + * version where those names are shortened to <=16 characters. + * + * Data source: OpenTelemetry metrics example (https://github.com/open-telemetry/opentelemetry-proto/blob/b363281e5c30f343bfd2405519cc3db93d11f252/examples/metrics.json) + * Licensed under Apache License 2.0. + */ +@State(Scope.Benchmark) +public class LongFieldNameCache { + @Param({"OTLP", "SHORT"}) + public String payload; + + private byte[] utf8Bytes; + + @Setup + public void setup() throws IOException { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + try (InputStream input = LongFieldNameCache.class.getClassLoader().getResourceAsStream("data/otlp-metrics.json")) { + if (input == null) { + throw new IOException("Missing data/otlp-metrics.json"); + } + byte[] buffer = new byte[1024]; + int count; + while ((count = input.read(buffer)) != -1) { + output.write(buffer, 0, count); + } + } + String json = new String(output.toByteArray(), StandardCharsets.UTF_8); + + if ("SHORT".equals(payload)) { + // Replace long property names with shorter equivalents, preserving JSON structure. + // We only replace complete keys including quotes and colon to avoid affecting values. + json = json.replace("\"startTimeUnixNano\":", "\"startTime\":"); + json = json.replace("\"aggregationTemporality\":", "\"temporality\":"); + json = json.replace("\"exponentialHistogram\":", "\"expHistogram\":"); + } + utf8Bytes = json.getBytes(StandardCharsets.UTF_8); + } + + @Benchmark + public Object parse() { + return JSON.parseObject(utf8Bytes); + } +} diff --git a/benchmark/src/main/resources/data/otlp-metrics.LICENSE b/benchmark/src/main/resources/data/otlp-metrics.LICENSE new file mode 100644 index 0000000000..f7c2b5a07e --- /dev/null +++ b/benchmark/src/main/resources/data/otlp-metrics.LICENSE @@ -0,0 +1,6 @@ +Source: OpenTelemetry opentelemetry-proto, examples/metrics.json +https://github.com/open-telemetry/opentelemetry-proto/blob/b363281e5c30f343bfd2405519cc3db93d11f252/examples/metrics.json +Git blob: 33e72c4b53aa9fdad6549de5e6e10251aa0a5236 + +Licensed under the Apache License, Version 2.0. The license text is provided +in the repository LICENSE file. diff --git a/benchmark/src/main/resources/data/otlp-metrics.json b/benchmark/src/main/resources/data/otlp-metrics.json new file mode 100644 index 0000000000..33e72c4b53 --- /dev/null +++ b/benchmark/src/main/resources/data/otlp-metrics.json @@ -0,0 +1,140 @@ +{ + "resourceMetrics": [ + { + "resource": { + "attributes": [ + { + "key": "service.name", + "value": { + "stringValue": "my.service" + } + } + ] + }, + "scopeMetrics": [ + { + "scope": { + "name": "my.library", + "version": "1.0.0", + "attributes": [ + { + "key": "my.scope.attribute", + "value": { + "stringValue": "some scope attribute" + } + } + ] + }, + "metrics": [ + { + "name": "my.counter", + "unit": "1", + "description": "I am a Counter", + "sum": { + "aggregationTemporality": 1, + "isMonotonic": true, + "dataPoints": [ + { + "asDouble": 5, + "startTimeUnixNano": "1544712660300000000", + "timeUnixNano": "1544712660300000000", + "attributes": [ + { + "key": "my.counter.attr", + "value": { + "stringValue": "some value" + } + } + ] + } + ] + } + }, + { + "name": "my.gauge", + "unit": "1", + "description": "I am a Gauge", + "gauge": { + "dataPoints": [ + { + "asDouble": 10, + "timeUnixNano": "1544712660300000000", + "attributes": [ + { + "key": "my.gauge.attr", + "value": { + "stringValue": "some value" + } + } + ] + } + ] + } + }, + { + "name": "my.histogram", + "unit": "1", + "description": "I am a Histogram", + "histogram": { + "aggregationTemporality": 1, + "dataPoints": [ + { + "startTimeUnixNano": "1544712660300000000", + "timeUnixNano": "1544712660300000000", + "count": "2", + "sum": 2, + "bucketCounts": ["1","1"], + "explicitBounds": [1], + "min": 0, + "max": 2, + "attributes": [ + { + "key": "my.histogram.attr", + "value": { + "stringValue": "some value" + } + } + ] + } + ] + } + }, + { + "name": "my.exponential.histogram", + "unit": "1", + "description": "I am an Exponential Histogram", + "exponentialHistogram": { + "aggregationTemporality": 1, + "dataPoints": [ + { + "startTimeUnixNano": "1544712660300000000", + "timeUnixNano": "1544712660300000000", + "count": "3", + "sum": 10, + "scale": 0, + "zeroCount": "1", + "positive": { + "offset": 1, + "bucketCounts": ["0","2"] + }, + "min": 0, + "max": 5, + "zeroThreshold": 0, + "attributes": [ + { + "key": "my.exponential.histogram.attr", + "value": { + "stringValue": "some value" + } + } + ] + } + ] + } + } + ] + } + ] + } + ] +} diff --git a/core/src/main/java/com/alibaba/fastjson2/JSONFactory.java b/core/src/main/java/com/alibaba/fastjson2/JSONFactory.java index 195410b352..f9f830d377 100644 --- a/core/src/main/java/com/alibaba/fastjson2/JSONFactory.java +++ b/core/src/main/java/com/alibaba/fastjson2/JSONFactory.java @@ -94,6 +94,8 @@ public static String getProperty(String key) { static final NameCacheEntry[] NAME_CACHE = new NameCacheEntry[8192]; static final NameCacheEntry2[] NAME_CACHE2 = new NameCacheEntry2[8192]; + // Longer names do not displace the existing short-name entries. + static final String[] NAME_CACHE3 = new String[8192]; static int defaultDecimalMaxScale = 2048; static int defaultMaxLevel; diff --git a/core/src/main/java/com/alibaba/fastjson2/JSONReaderASCII.java b/core/src/main/java/com/alibaba/fastjson2/JSONReaderASCII.java index b58d2f59b2..acd0dd4d92 100644 --- a/core/src/main/java/com/alibaba/fastjson2/JSONReaderASCII.java +++ b/core/src/main/java/com/alibaba/fastjson2/JSONReaderASCII.java @@ -1200,6 +1200,9 @@ public final String readFieldName() { + (bytes[nameBegin + 8] & 0xFFL); break; default: + if (length >= 17 && length <= 32 && IOUtils.isASCII(bytes, nameBegin, length)) { + return getFieldNameUTF8Cache3(nameBegin, length); + } break; } diff --git a/core/src/main/java/com/alibaba/fastjson2/JSONReaderUTF8.java b/core/src/main/java/com/alibaba/fastjson2/JSONReaderUTF8.java index b17cb1d5ba..3299795e88 100644 --- a/core/src/main/java/com/alibaba/fastjson2/JSONReaderUTF8.java +++ b/core/src/main/java/com/alibaba/fastjson2/JSONReaderUTF8.java @@ -3574,6 +3574,9 @@ public String readFieldName() { + ((long) bytes[nameBegin + 8]); break; default: + if (length >= 17 && length <= 32) { + return getFieldNameUTF8Cache3(nameBegin, length); + } break; } @@ -3641,6 +3644,49 @@ public String readFieldName() { return getFieldName(); } + final String getFieldNameUTF8Cache3(int nameBegin, int length) { + final byte[] bytes = this.bytes; + // Boundary bytes keep hashing cheap; the full name comparison below disambiguates the middle. + int hash = length; + for (int i = 0; i < 8; i++) { + hash = hash * 31 + (bytes[nameBegin + i] & 0xff); + } + for (int i = length - 8; i < length; i++) { + hash = hash * 31 + (bytes[nameBegin + i] & 0xff); + } + hash ^= (hash >>> 16); + hash *= 0x85ebca6b; + hash ^= (hash >>> 13); + int index = hash & (NAME_CACHE3.length - 1); + String cached = NAME_CACHE3[index]; + if (cached != null && cached.length() == length) { + boolean match = true; + for (int i = 0; i < length; i++) { + if (cached.charAt(i) != (char) (bytes[nameBegin + i] & 0xff)) { + match = false; + break; + } + } + if (match) { + return cached; + } + } + String name; + if (STRING_CREATOR_JDK8 != null) { + name = asciiStringJDK8(bytes, nameBegin, length); + } else if (ANDROID) { + name = getLatin1String(nameBegin, length); + } else if (STRING_CREATOR_JDK11 != null) { + name = STRING_CREATOR_JDK11.apply( + Arrays.copyOfRange(bytes, nameBegin, nameBegin + length), + LATIN1); + } else { + name = new String(bytes, nameBegin, length, ISO_8859_1); + } + NAME_CACHE3[index] = name; + return name; + } + @Override public final int readInt32Value() { int ch = this.ch; diff --git a/core/src/test/java/com/alibaba/fastjson2/JSONFactoryNameCacheTest.java b/core/src/test/java/com/alibaba/fastjson2/JSONFactoryNameCacheTest.java index 85d919693b..de21c1c9f5 100644 --- a/core/src/test/java/com/alibaba/fastjson2/JSONFactoryNameCacheTest.java +++ b/core/src/test/java/com/alibaba/fastjson2/JSONFactoryNameCacheTest.java @@ -2,16 +2,24 @@ import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Random; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import static com.alibaba.fastjson2.JSONFactory.NAME_CACHE; import static com.alibaba.fastjson2.JSONFactory.NAME_CACHE2; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; @Tag("util") @@ -41,6 +49,174 @@ public void test() throws Exception { latch.await(); } + @ParameterizedTest + @ValueSource(ints = {17, 22, 31, 32}) + void longAsciiNameReused(int len) { + String name = asciiName(len); + byte[] bytes = jsonBytes(name, 123); + JSONObject one = JSON.parseObject(bytes); + JSONObject two = JSON.parseObject(bytes); + int expectedValue = 123; + assertEquals(expectedValue, one.getIntValue(name)); + assertEquals(expectedValue, two.getIntValue(name)); + assertSame(one.keySet().iterator().next(), two.keySet().iterator().next()); + } + + @Test + void shortAsciiNamesStillReused() { + Arrays.fill(NAME_CACHE, null); + Arrays.fill(NAME_CACHE2, null); + int[] lengths = {8, 16}; + for (int len : lengths) { + String name = asciiName(len); + byte[] bytes = jsonBytes(name, 456); + JSONObject one = JSON.parseObject(bytes); + JSONObject two = JSON.parseObject(bytes); + int expectedValue = 456; + assertEquals(expectedValue, one.getIntValue(name)); + assertEquals(expectedValue, two.getIntValue(name)); + assertSame(one.keySet().iterator().next(), two.keySet().iterator().next()); + } + } + + @Test + void boundaryAndEscapedNamesKeepValues() { + String[] names = {asciiName(33), "abcdefghijklmnop你好", "abcdefghijklmnop\"", + "abcdefghijklmnop\\", "abcdefghijklmnop" + (char) 0}; + for (String name : names) { + assertDecodedName(jsonBytes(name, 111), name, 111); + } + String encoded = JSON.toJSONString("abcdefghijklmnopA").replace("A", "\\" + "u0041"); + assertDecodedName(("{" + encoded + ":222}").getBytes(StandardCharsets.UTF_8), "abcdefghijklmnopA", 222); + } + + @Test + void differentMiddleBytesKeepDistinctKeys() { + String name1 = "prefixABmiddle01suffixYZ"; + String name2 = "prefixABmiddle02suffixYZ"; + String name3 = "prefixABmiddle01middle01suffixYZ"; + String name4 = "prefixABmiddle02middle02suffixYZ"; + + for (int i = 0; i < 50; i++) { + JSONObject obj = new JSONObject(); + obj.put(name1, 1); + obj.put(name2, 2); + obj.put(name3, 3); + obj.put(name4, 4); + byte[] bytes = obj.toString().getBytes(StandardCharsets.UTF_8); + JSONObject parsed = JSON.parseObject(bytes); + assertEquals(4, parsed.size()); + assertEquals(1, parsed.getIntValue(name1)); + assertEquals(2, parsed.getIntValue(name2)); + assertEquals(3, parsed.getIntValue(name3)); + assertEquals(4, parsed.getIntValue(name4)); + } + } + + @Test + void offsetAndReusedBufferKeepValues() { + String name1 = asciiName(17); + String name2 = asciiName(18); + int val1 = 100; + int val2 = 200; + byte[] jsonBytes1 = jsonBytes(name1, val1); + byte[] jsonBytes2 = jsonBytes(name2, val2); + + for (int i = 0; i < 100; i++) { + byte[] buffer = new byte[256]; + Arrays.fill(buffer, (byte) 'x'); + int offset = 5; + System.arraycopy(jsonBytes1, 0, buffer, offset, jsonBytes1.length); + JSONObject one = JSON.parseObject(buffer, offset, jsonBytes1.length, StandardCharsets.UTF_8, JSONObject.class); + assertEquals(val1, one.getIntValue(name1)); + + System.arraycopy(jsonBytes2, 0, buffer, offset, jsonBytes2.length); + JSONObject two = JSON.parseObject(buffer, offset, jsonBytes2.length, StandardCharsets.UTF_8, JSONObject.class); + assertEquals(val2, two.getIntValue(name2)); + } + } + + @Test + void concurrentLongNamesKeepValues() throws Exception { + ExecutorService executor = Executors.newFixedThreadPool(8); + Future[] futures = new Future[8]; + try { + for (int t = 0; t < 8; t++) { + futures[t] = executor.submit(() -> { + for (int i = 0; i < 1000; i++) { + String name = "nameWithLongPrefix" + (i % 100); + int value = i; + byte[] bytes = jsonBytes(name, value); + JSONObject obj = JSON.parseObject(bytes); + assertEquals(value, obj.getIntValue(name)); + } + }); + } + for (Future future : futures) { + future.get(10, TimeUnit.SECONDS); + } + } finally { + executor.shutdownNow(); + assertTrue(executor.awaitTermination(10, TimeUnit.SECONDS)); + } + } + + private static String asciiName(int len) { + StringBuilder sb = new StringBuilder(len); + for (int i = 0; i < len; i++) { + sb.append((char) ('a' + (i % 26))); + } + return sb.toString(); + } + + private static byte[] jsonBytes(String name, int value) { + return ("{" + JSON.toJSONString(name) + ":" + value + "}").getBytes(StandardCharsets.UTF_8); + } + + private static void assertDecodedName(byte[] jsonBytes, String name, int expectedValue) { + JSONObject one = JSON.parseObject(jsonBytes); + JSONObject two = JSON.parseObject(jsonBytes); + assertEquals(expectedValue, one.getIntValue(name)); + assertEquals(expectedValue, two.getIntValue(name)); + } + + @ParameterizedTest + @ValueSource(ints = {17, 22, 31, 32}) + void directUtf8ReaderReusesName(int len) { + char[] chars = new char[len]; + Arrays.fill(chars, 'a'); + String name = new String(chars); + byte[] data = ("{\"" + name + "\":123}").getBytes(StandardCharsets.UTF_8); + String key1 = directUtf8Name(data); + String key2 = directUtf8Name(data); + assertEquals(name, key1); + assertEquals(name, key2); + assertSame(key1, key2); + } + + private String directUtf8Name(byte[] data) { + try (JSONReader reader = JSONReader.of(data, 0, data.length, JSONFactory.createReadContext())) { + assertTrue(reader.nextIfObjectStart()); + String key = reader.readFieldName(); + int value = reader.readInt32Value(); + assertEquals(123, value); + assertTrue(reader.nextIfObjectEnd()); + return key; + } + } + + @Test + void latin1NonAsciiNamesRemainCorrect() { + String name = "abcdefghijklmnopé"; + String json = "{" + JSON.toJSONString(name) + ":123}"; + byte[] isoBytes = json.getBytes(StandardCharsets.ISO_8859_1); + JSONObject obj1 = JSON.parseObject(json, JSONObject.class); + JSONObject obj2 = JSON.parseObject(isoBytes, 0, isoBytes.length, StandardCharsets.ISO_8859_1, JSONObject.class); + assertEquals(123, obj1.getIntValue(name)); + assertEquals(123, obj2.getIntValue(name)); + assertNotSame(obj1.keySet().iterator().next(), obj2.keySet().iterator().next()); + } + public static class Task implements Runnable { final CountDownLatch latch; From 53192789fce7388cddd3c5463dd051c3d693e52e Mon Sep 17 00:00:00 2001 From: hutiefang76 <137664623+hutiefang76@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:24:02 +0800 Subject: [PATCH 2/3] docs: avoid malformed HTML in long-name benchmark Javadoc --- .../com/alibaba/fastjson2/benchmark/LongFieldNameCache.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/LongFieldNameCache.java b/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/LongFieldNameCache.java index 4804440f88..f7c9c5a20b 100644 --- a/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/LongFieldNameCache.java +++ b/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/LongFieldNameCache.java @@ -16,7 +16,7 @@ * Benchmark for long field name caching in fastjson2. * Compares parsing performance with standard OTLP metrics JSON containing long property names * (e.g., startTimeUnixNano, aggregationTemporality, exponentialHistogram) versus a modified - * version where those names are shortened to <=16 characters. + * version where those names are shortened to 16 characters or fewer. * * Data source: OpenTelemetry metrics example (https://github.com/open-telemetry/opentelemetry-proto/blob/b363281e5c30f343bfd2405519cc3db93d11f252/examples/metrics.json) * Licensed under Apache License 2.0. From 52c023be5b76bc6c54808427f7b95dec8e18bc90 Mon Sep 17 00:00:00 2001 From: hutiefang76 <137664623+hutiefang76@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:50:44 +0800 Subject: [PATCH 3/3] test: cover long ASCII field name caching --- .../fastjson2/JSONFactoryNameCacheTest.java | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/core/src/test/java/com/alibaba/fastjson2/JSONFactoryNameCacheTest.java b/core/src/test/java/com/alibaba/fastjson2/JSONFactoryNameCacheTest.java index de21c1c9f5..d3fd0faf0d 100644 --- a/core/src/test/java/com/alibaba/fastjson2/JSONFactoryNameCacheTest.java +++ b/core/src/test/java/com/alibaba/fastjson2/JSONFactoryNameCacheTest.java @@ -217,6 +217,57 @@ void latin1NonAsciiNamesRemainCorrect() { assertNotSame(obj1.keySet().iterator().next(), obj2.keySet().iterator().next()); } + @ParameterizedTest + @ValueSource(ints = {17, 24, 25, 32}) + void iso8859_1LongAsciiNamesReused(int len) { + String name = asciiName(len); + byte[] bytes = jsonBytes(name, 123); + JSONObject one = JSON.parseObject(bytes, 0, bytes.length, StandardCharsets.ISO_8859_1, JSONObject.class); + JSONObject two = JSON.parseObject(bytes, 0, bytes.length, StandardCharsets.ISO_8859_1, JSONObject.class); + assertEquals(123, one.getIntValue(name)); + assertEquals(123, two.getIntValue(name)); + assertSame(one.keySet().iterator().next(), two.keySet().iterator().next()); + } + + @Test + void latin1DistinctNamesRemainDistinct() { + String name1 = "prefixABmiddle01suffixYZ"; + String name2 = "prefixABmiddle02suffixYZ"; + byte[] isoBytes = ("{" + JSON.toJSONString(name1) + ":1," + JSON.toJSONString(name2) + ":2}").getBytes(StandardCharsets.ISO_8859_1); + for (int i = 0; i < 20; i++) { + JSONObject obj = JSON.parseObject(isoBytes, 0, isoBytes.length, StandardCharsets.ISO_8859_1, JSONObject.class); + assertEquals(2, obj.size()); + assertEquals(1, obj.getIntValue(name1)); + assertEquals(2, obj.getIntValue(name2)); + } + } + + @Test + void offsetAndReusedBufferIso8859_1KeepValues() { + String name1 = asciiName(17); + String name2 = asciiName(24); + int val1 = 100; + int val2 = 200; + byte[] jsonBytes1 = jsonBytes(name1, val1); + byte[] jsonBytes2 = jsonBytes(name2, val2); + byte[] buffer = new byte[256]; + Arrays.fill(buffer, (byte) 'x'); + int offset = 5; + System.arraycopy(jsonBytes1, 0, buffer, offset, jsonBytes1.length); + JSONObject one = JSON.parseObject(buffer, offset, jsonBytes1.length, StandardCharsets.ISO_8859_1, JSONObject.class); + assertEquals(val1, one.getIntValue(name1)); + assertEquals(1, one.size()); + + Arrays.fill(buffer, (byte) 'x'); + System.arraycopy(jsonBytes2, 0, buffer, offset, jsonBytes2.length); + JSONObject two = JSON.parseObject(buffer, offset, jsonBytes2.length, StandardCharsets.ISO_8859_1, JSONObject.class); + assertEquals(val2, two.getIntValue(name2)); + + assertEquals(val1, one.getIntValue(name1)); + assertEquals(1, one.size()); + assertNotSame(one.keySet().iterator().next(), two.keySet().iterator().next()); + } + public static class Task implements Runnable { final CountDownLatch latch;