This is an automated email from the ASF dual-hosted git repository.

garydgregory pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/commons-lang.git

commit 77f62098415696b103bd7c83dc61e98cbe9110c2
Author: Gary Gregory <[email protected]>
AuthorDate: Wed Nov 18 13:37:20 2026 -0500

    Avoid repeated array prefix copies in ClassUtils (#1886)
    
    Count array dimensions and build the suffix in one pass, then strip
    the prefix with a single substring operation.
    
    Expand String overload tests for primitive, reference, and nested-class
    arrays through 255 dimensions. Cover existing behavior for excessive
    dimensions and bracket-only inputs.
    
    Add a JMH benchmark for valid class names and a release note.
    
    Assisted-By: OpenAI Codex
---
 src/changes/changes.xml                            |   1 +
 .../java/org/apache/commons/lang3/ClassUtils.java  |   7 +-
 .../ClassUtilsGetShortClassNameBenchmark.java      | 114 +++++++++++++++++++++
 .../org/apache/commons/lang3/ClassUtilsTest.java   |  33 ++++++
 4 files changed, 153 insertions(+), 2 deletions(-)

diff --git a/src/changes/changes.xml b/src/changes/changes.xml
index c7d8acee4..e75779ddf 100644
--- a/src/changes/changes.xml
+++ b/src/changes/changes.xml
@@ -106,6 +106,7 @@ The <action> type attribute can be add,update,fix,remove.
     <action                   type="fix" dev="ggregory" due-to="Gary Gregory, 
Amar Ghugare">Preserve negative durations in DurationUtils.accept so 
ThreadUtils.sleep, ThreadUtils.sleepQuietly, ThreadUtils.join, and 
ObjectUtils.wait reject negative sub-millisecond timeouts (#1882).</action>
     <action                   type="fix" dev="ggregory" due-to="Gary Gregory, 
Amar Ghugare">Preserve defining class loaders throughout object graphs in 
SerializationUtils.clone() and roundtrip().</action>
     <action                   type="fix" dev="ggregory" due-to="Gary Gregory, 
Faris Basha TM">Javadoc: Fix dead links to the 3.6 release notes 
(#1885).</action>
+    <action                   type="fix" dev="ggregory" due-to="Gary Gregory, 
joao-jordy">Avoid repeated array prefix copies in 
ClassUtils.getShortClassName(String) (#1886).</action>
     <!-- ADD -->
     <!-- UPDATE -->
   </release>
diff --git a/src/main/java/org/apache/commons/lang3/ClassUtils.java 
b/src/main/java/org/apache/commons/lang3/ClassUtils.java
index efd55965d..5c07a801d 100644
--- a/src/main/java/org/apache/commons/lang3/ClassUtils.java
+++ b/src/main/java/org/apache/commons/lang3/ClassUtils.java
@@ -1225,10 +1225,13 @@ public static String getShortClassName(String 
className) {
         final StringBuilder arrayPrefix = new StringBuilder();
         // Handle array encoding
         if (className.startsWith("[")) {
-            while (className.charAt(0) == '[') {
-                className = className.substring(1);
+            // Strip the prefix once to avoid copying the string for each 
dimension.
+            int dim = 0;
+            while (className.charAt(dim) == '[') {
+                dim++;
                 arrayPrefix.append("[]");
             }
+            className = className.substring(dim);
             // Strip Object type encoding
             if (className.charAt(0) == 'L' && 
className.charAt(className.length() - 1) == ';') {
                 className = className.substring(1, className.length() - 1);
diff --git 
a/src/test/java/org/apache/commons/lang3/ClassUtilsGetShortClassNameBenchmark.java
 
b/src/test/java/org/apache/commons/lang3/ClassUtilsGetShortClassNameBenchmark.java
new file mode 100644
index 000000000..9be4deef4
--- /dev/null
+++ 
b/src/test/java/org/apache/commons/lang3/ClassUtilsGetShortClassNameBenchmark.java
@@ -0,0 +1,114 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.commons.lang3;
+
+import java.lang.reflect.Array;
+import java.util.concurrent.TimeUnit;
+
+import org.openjdk.jmh.annotations.Benchmark;
+import org.openjdk.jmh.annotations.BenchmarkMode;
+import org.openjdk.jmh.annotations.Fork;
+import org.openjdk.jmh.annotations.Measurement;
+import org.openjdk.jmh.annotations.Mode;
+import org.openjdk.jmh.annotations.OutputTimeUnit;
+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 org.openjdk.jmh.annotations.Warmup;
+
+/**
+ * Benchmarks {@link ClassUtils#getShortClassName(String)} with valid JVM 
class names.
+ *
+ * <p>
+ * Compare a baseline revision from before the optimization with the updated 
code in separate checkouts. Copy this benchmark source unchanged into both
+ * checkouts, including the baseline if it does not contain the benchmark. Use 
the same JDK, machine, and JVM options, and record both source revisions
+ * with the results. Run the checkouts sequentially to avoid interference 
between measurements.
+ * </p>
+ *
+ * <p>
+ * Run these POSIX shell commands from the baseline checkout, then repeat them 
from the updated checkout with
+ * {@code benchmark_result=/tmp/classutils-after.json}. The JSON files are 
outside {@code target} so that a clean build preserves the comparison results.
+ * Ensure {@code java} and Maven use the same JDK. The GC profiler reports 
allocation per operation as {@code gc.alloc.rate.norm}, in bytes per operation.
+ * </p>
+ *
+ * <pre>
+ * benchmark_result=/tmp/classutils-before.json
+ * mvn -B -ntp -Pbenchmark clean test-compile dependency:build-classpath 
-Dmdep.outputFile=target/benchmark-classpath.txt
+ * java -cp "target/test-classes:target/classes:$(cat 
target/benchmark-classpath.txt)" \
+ *   org.openjdk.jmh.Main 
org.apache.commons.lang3.ClassUtilsGetShortClassNameBenchmark \
+ *   -prof gc -jvmArgs "-Xms256m -Xmx256m" -rf json -rff "$benchmark_result"
+ * </pre>
+ *
+ * <p>
+ * Each parameter combination uses three JVM forks, with five one-second 
warmup iterations and five one-second measurement iterations per fork.
+ * Shortened runs are useful for checking the benchmark, but use the full 
configuration and inspect measurement uncertainty before reporting timing
+ * differences. Compare execution time and allocation for matching parameter 
combinations; an improvement for deeply nested arrays does not imply
+ * an improvement for ordinary class names or shallow arrays.
+ * </p>
+ */
+@BenchmarkMode(Mode.AverageTime)
+@OutputTimeUnit(TimeUnit.NANOSECONDS)
+@State(Scope.Thread)
+@Fork(3)
+@Warmup(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
+@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
+public class ClassUtilsGetShortClassNameBenchmark {
+
+    /**
+     * The array depth, or zero for a non-array class.
+     */
+    @Param({ "0", "1", "2", "32", "255" })
+    public int dimensions;
+
+    /**
+     * The primitive, reference, or nested class used as the array element 
type.
+     */
+    @Param({ "int", "java.lang.String", "java.util.Map$Entry" })
+    public String elementType;
+
+    private String className;
+
+    /**
+     * Constructs a benchmark state.
+     */
+    public ClassUtilsGetShortClassNameBenchmark() {
+        // Empty.
+    }
+
+    /**
+     * Gets the short class name of the prepared input.
+     *
+     * @return the short class name.
+     */
+    @Benchmark
+    public String getShortClassName() {
+        return ClassUtils.getShortClassName(className);
+    }
+
+    /**
+     * Prepares a valid JVM class name outside the measured operation.
+     *
+     * @throws ClassNotFoundException if the element type cannot be loaded.
+     */
+    @Setup
+    public void setup() throws ClassNotFoundException {
+        final Class<?> elementClass = ClassUtils.getClass(elementType);
+        className = dimensions == 0 ? elementClass.getName() : 
Array.newInstance(elementClass, new int[dimensions]).getClass().getName();
+    }
+}
diff --git a/src/test/java/org/apache/commons/lang3/ClassUtilsTest.java 
b/src/test/java/org/apache/commons/lang3/ClassUtilsTest.java
index 032a1b971..e98f4b79a 100644
--- a/src/test/java/org/apache/commons/lang3/ClassUtilsTest.java
+++ b/src/test/java/org/apache/commons/lang3/ClassUtilsTest.java
@@ -49,6 +49,7 @@
 import org.apache.commons.lang3.reflect.testbed.StringParameterizedChild;
 import org.junit.jupiter.api.Test;
 import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
 import org.junitpioneer.jupiter.params.IntRangeSource;
 
 /**
@@ -719,6 +720,38 @@ void test_getShortClassName_String() {
         assertEquals("", ClassUtils.getShortClassName(""));
     }
 
+    @ParameterizedTest
+    @ValueSource(ints = { 1, 2, MAX_ARRAY_DIMENSIONS })
+    void test_getShortClassName_String_Array(final int dimensions) {
+        final String prefix = StringUtils.repeat('[', dimensions);
+        final String suffix = StringUtils.repeat("[]", dimensions);
+        assertEquals("boolean" + suffix, ClassUtils.getShortClassName(prefix + 
"Z"));
+        assertEquals("byte" + suffix, ClassUtils.getShortClassName(prefix + 
"B"));
+        assertEquals("char" + suffix, ClassUtils.getShortClassName(prefix + 
"C"));
+        assertEquals("short" + suffix, ClassUtils.getShortClassName(prefix + 
"S"));
+        assertEquals("int" + suffix, ClassUtils.getShortClassName(prefix + 
"I"));
+        assertEquals("long" + suffix, ClassUtils.getShortClassName(prefix + 
"J"));
+        assertEquals("float" + suffix, ClassUtils.getShortClassName(prefix + 
"F"));
+        assertEquals("double" + suffix, ClassUtils.getShortClassName(prefix + 
"D"));
+        assertEquals("String" + suffix, ClassUtils.getShortClassName(prefix + 
"Ljava.lang.String;"));
+        assertEquals("Map.Entry" + suffix, ClassUtils.getShortClassName(prefix 
+ "Ljava.util.Map$Entry;"));
+        assertEquals("Outer.Inner" + suffix, 
ClassUtils.getShortClassName(prefix + "LOuter$Inner;"));
+    }
+
+    @ParameterizedTest
+    @ValueSource(strings = { "[", "[[", "[[[" })
+    void test_getShortClassName_String_BracketsOnly(final String className) {
+        assertThrows(StringIndexOutOfBoundsException.class, () -> 
ClassUtils.getShortClassName(className));
+    }
+
+    @Test
+    void test_getShortClassName_String_ExcessiveDimensions() {
+        // This method does not validate class names, including dimensions 
beyond the JVM limit.
+        final int dimensions = 1000;
+        final String className = StringUtils.repeat('[', dimensions) + 
"Ljava.lang.String;";
+        assertEquals("String" + StringUtils.repeat("[]", dimensions), 
ClassUtils.getShortClassName(className));
+    }
+
     @Test
     void test_getSimpleName_Class() {
         assertEquals("ClassUtils", ClassUtils.getSimpleName(ClassUtils.class));

Reply via email to