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


The following commit(s) were added to refs/heads/master by this push:
     new 25b33020c Optimize StringUtils.replaceEach scanning and text copying 
(#1894)
25b33020c is described below

commit 25b33020cac4ff9e40095f6d1268f2f347fbbd64
Author: Gary Gregory <[email protected]>
AuthorDate: Thu Nov 26 11:21:34 2026 -0500

    Optimize StringUtils.replaceEach scanning and text copying (#1894)
    
    Cache each rule's next match to avoid repeated suffix scans.
    Copy unchanged text ranges in bulk, skipping empty ranges.
    
    Preserve overlap handling, search-order ties, and repeated-pass
    behavior. Add Unicode regression tests and JMH benchmarks for
    different match distributions.
    
    The cached match positions in this PR address the repeated suffix scans.
    I tested a small additional optimization: copy unchanged text using
    StringBuilder.append(text, start, end) instead of appending individual
    characters, and skip empty gaps between matches.
    
    This retains PR 1893 matching algorithm and bookkeeping while reducing
    copying overhead, particularly when replacements are sparse.
    
    I compared both implementations using the same benchmark:
    Input distribution      PR      With range copying      Speedup
    Grouped 9.763 µs        8.880 µs        1.10×
    Grouped, UTF-16 16.242 µs       14.559 µs       1.12×
    Interleaved     21.613 µs       20.177 µs       1.07×
    Sparse, match at end    10.504 µs       0.934 µs        11.24×
    Sparse, match in middle 9.878 µs        0.951 µs        10.39×
    Sparse, UTF-16  6.135 µs        2.239 µs        2.74×
    No match        0.723 µs        0.724 µs        ≈1.00×
    Single pattern  7.359 µs        6.149 µs        1.20×
    
    These are mean times per operation from JMH 1.37 on OpenJDK 17.0.21.1,
    with inputs of 4,096 UTF-16 code units, two forks, three 500 ms warmup
    iterations and five 500 ms measurement iterations per fork, -Xms256m
    -Xmx256m, and the GC profiler.
    
    The largest gains come from copying long unchanged ranges. No-match
    timings overlap within measurement error. These are synthetic API
    measurements; application-level gains will depend on the workload.
    
    Validation of the combined change:
    - The complete default Maven build passed: 111,689 tests, zero
    failures/errors, 29 skipped, including coverage and static checks.
    - 404,800 behavior comparisons on each of JDK 8, 17, and 21 matched the
    PR’s outputs, exception types/messages, and unchanged-input reference
    identity.
    - Added regression coverage for unchanged ranges containing
    supplementary characters and unpaired surrogate code units, including
    repeated replacement passes.
---
 .../java/org/apache/commons/lang3/StringUtils.java |  44 +++---
 .../lang3/StringUtilsReplaceEachBenchmark.java     | 148 +++++++++++++++++++++
 .../org/apache/commons/lang3/StringUtilsTest.java  |  42 ++++++
 3 files changed, 206 insertions(+), 28 deletions(-)

diff --git a/src/main/java/org/apache/commons/lang3/StringUtils.java 
b/src/main/java/org/apache/commons/lang3/StringUtils.java
index cf94148f0..3c1d5b4e4 100644
--- a/src/main/java/org/apache/commons/lang3/StringUtils.java
+++ b/src/main/java/org/apache/commons/lang3/StringUtils.java
@@ -6600,8 +6600,8 @@ private static String replaceEachOnce(final String text, 
final String[] searchLi
                 + replacementLength);
         }
 
-        // keep track of which still have matches
-        final boolean[] noMoreMatchesForReplIndex = new boolean[searchLength];
+        // Keep the next match for each rule so that distant matches are not 
searched for again after every replacement.
+        final int[] nextMatchIndices = new int[searchLength];
 
         // index on index that the match was found
         int textIndex = -1;
@@ -6609,22 +6609,14 @@ private static String replaceEachOnce(final String 
text, final String[] searchLi
         int tempIndex;
 
         // index of replace array that will replace the search string found
-        // NOTE: logic duplicated below START
         for (int i = 0; i < searchLength; i++) {
-            if (noMoreMatchesForReplIndex[i] || isEmpty(searchList[i]) || 
replacementList[i] == null) {
-                continue;
-            }
-            tempIndex = text.indexOf(searchList[i]);
-
-            // see if we need to keep searching for this
-            if (tempIndex == -1) {
-                noMoreMatchesForReplIndex[i] = true;
-            } else if (textIndex == -1 || tempIndex < textIndex) {
+            tempIndex = isEmpty(searchList[i]) || replacementList[i] == null ? 
-1 : text.indexOf(searchList[i]);
+            nextMatchIndices[i] = tempIndex;
+            if (tempIndex != -1 && (textIndex == -1 || tempIndex < textIndex)) 
{
                 textIndex = tempIndex;
                 replaceIndex = i;
             }
         }
-        // NOTE: logic mostly below END
 
         // no search strings found, we are done
         if (textIndex == -1) {
@@ -6652,8 +6644,8 @@ private static String replaceEachOnce(final String text, 
final String[] searchLi
 
         while (textIndex != -1) {
 
-            for (int i = start; i < textIndex; i++) {
-                buf.append(text.charAt(i));
+            if (start < textIndex) {
+                buf.append(text, start, textIndex);
             }
             buf.append(replacementList[replaceIndex]);
 
@@ -6662,28 +6654,24 @@ private static String replaceEachOnce(final String 
text, final String[] searchLi
             textIndex = -1;
             replaceIndex = -1;
             // find the next earliest match
-            // NOTE: logic mostly duplicated above START
             for (int i = 0; i < searchLength; i++) {
-                if (noMoreMatchesForReplIndex[i] || isEmpty(searchList[i]) || 
replacementList[i] == null) {
+                tempIndex = nextMatchIndices[i];
+                if (tempIndex == -1) {
                     continue;
                 }
-                tempIndex = text.indexOf(searchList[i], start);
-
-                // see if we need to keep searching for this
-                if (tempIndex == -1) {
-                    noMoreMatchesForReplIndex[i] = true;
-                } else if (textIndex == -1 || tempIndex < textIndex) {
+                if (tempIndex < start) {
+                    // A replacement may consume this match, including a match 
of another overlapping rule.
+                    tempIndex = text.indexOf(searchList[i], start);
+                    nextMatchIndices[i] = tempIndex;
+                }
+                if (tempIndex != -1 && (textIndex == -1 || tempIndex < 
textIndex)) {
                     textIndex = tempIndex;
                     replaceIndex = i;
                 }
             }
-            // NOTE: logic duplicated above END
 
         }
-        final int textLength = text.length();
-        for (int i = start; i < textLength; i++) {
-            buf.append(text.charAt(i));
-        }
+        buf.append(text, start, text.length());
         return buf.toString();
     }
 
diff --git 
a/src/test/java/org/apache/commons/lang3/StringUtilsReplaceEachBenchmark.java 
b/src/test/java/org/apache/commons/lang3/StringUtilsReplaceEachBenchmark.java
new file mode 100644
index 000000000..2079d9188
--- /dev/null
+++ 
b/src/test/java/org/apache/commons/lang3/StringUtilsReplaceEachBenchmark.java
@@ -0,0 +1,148 @@
+/*
+ * 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.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 StringUtils#replaceEach(String, String[], String[])} with 
different match distributions.
+ * Grouped inputs place frequent ampersands before the other matching 
characters; interleaved inputs mix all five characters.
+ * Sparse, absent, and single-pattern cases measure paths that do not 
repeatedly search for distant matches.
+ * Sparse matches at the end and middle also measure copying unchanged Latin-1 
and UTF-16 ranges.
+ *
+ * <p>
+ * Run the same benchmark in baseline and candidate checkouts with the same 
JDK and JVM options. For example, in a POSIX shell:
+ * </p>
+ * <pre>
+ * 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 StringUtilsReplaceEachBenchmark -prof gc -jvmArgs 
"-Xms256m -Xmx256m" \
+ *   -rf json -rff /tmp/replace-each-before.json
+ * </pre>
+ * <p>
+ * Use a separate result file for the candidate. Compare both time and bytes 
allocated per operation, including the unaffected cases.
+ * </p>
+ *
+ * @since 3.22.1
+ */
+@BenchmarkMode(Mode.AverageTime)
+@OutputTimeUnit(TimeUnit.NANOSECONDS)
+@State(Scope.Thread)
+@Fork(2)
+@Warmup(iterations = 3, time = 1)
+@Measurement(iterations = 5, time = 1)
+public class StringUtilsReplaceEachBenchmark {
+
+    /**
+     * The distribution of matching characters in the input.
+     *
+     * @since 3.22.1
+     */
+    @Param({ "GROUPED", "UTF16_GROUPED", "INTERLEAVED", "SPARSE", 
"SPARSE_MIDDLE", "UTF16_SPARSE", "NO_MATCH", "SINGLE_PATTERN" })
+    public String distribution;
+
+    /**
+     * The number of UTF-16 code units in the input.
+     *
+     * @since 3.22.1
+     */
+    @Param({ "64", "4096", "65536" })
+    public int length;
+
+    private String[] replacements;
+    private String[] searches;
+    private String text;
+
+    /**
+     * Constructs a benchmark state.
+     *
+     * @since 3.22.1
+     */
+    public StringUtilsReplaceEachBenchmark() {
+        // Empty.
+    }
+
+    /**
+     * Replaces the prepared input, including all per-call search bookkeeping 
and output allocation.
+     *
+     * @return the replaced text.
+     * @since 3.22.1
+     */
+    @Benchmark
+    public String replaceEach() {
+        return StringUtils.replaceEach(text, searches, replacements);
+    }
+
+    /**
+     * Prepares the input and replacement rules outside the measured operation.
+     *
+     * @since 3.22.1
+     */
+    @Setup
+    public void setup() {
+        searches = new String[] { "&", "<", ">", "\"", "'" };
+        replacements = new String[] { "&amp;", "&lt;", "&gt;", "&quot;", 
"&apos;" };
+        final String unit;
+        switch (distribution) {
+        case "GROUPED":
+        case "SINGLE_PATTERN":
+            unit = "word &";
+            break;
+        case "UTF16_SPARSE":
+            unit = "\u4e2d\u6587 ";
+            break;
+        case "UTF16_GROUPED":
+            unit = "\u4e2d\u6587 &";
+            break;
+        case "INTERLEAVED":
+            unit = "word &<>\"'";
+            break;
+        default:
+            unit = "word ";
+            break;
+        }
+        final StringBuilder builder = new StringBuilder(length + 
unit.length());
+        while (builder.length() < length) {
+            builder.append(unit);
+        }
+        builder.setLength(length);
+        if (distribution.endsWith("GROUPED")) {
+            builder.replace(length - 4, length, "<>\"'");
+        } else if ("SPARSE".equals(distribution)) {
+            builder.setCharAt(length - 1, '&');
+        } else if ("SPARSE_MIDDLE".equals(distribution) || 
"UTF16_SPARSE".equals(distribution)) {
+            builder.setCharAt(length / 2, '&');
+        } else if ("SINGLE_PATTERN".equals(distribution)) {
+            searches = new String[] { "&" };
+            replacements = new String[] { "&amp;" };
+        }
+        text = builder.toString();
+    }
+}
diff --git a/src/test/java/org/apache/commons/lang3/StringUtilsTest.java 
b/src/test/java/org/apache/commons/lang3/StringUtilsTest.java
index 13fba8583..8977e93db 100644
--- a/src/test/java/org/apache/commons/lang3/StringUtilsTest.java
+++ b/src/test/java/org/apache/commons/lang3/StringUtilsTest.java
@@ -2234,6 +2234,48 @@ void testReplaceChars_StringStringString() {
                 
"nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM567891234"));
     }
 
+    @Test
+    void testReplaceEachDistantMatch() {
+        assertEquals("xxxxxxY", StringUtils.replaceEach("aaaaaab", new 
String[] { "a", "b" }, new String[] { "x", "Y" }));
+        assertEquals("Y", StringUtils.replaceEach("aaaaaab", new String[] { 
"a", "b" }, new String[] { "", "Y" }));
+    }
+
+    @Test
+    void testReplaceEachIgnoredRules() {
+        final String text = "abc";
+        assertSame(text, StringUtils.replaceEach(text, new String[] { null, 
"", "absent", "a" }, new String[] { "x", "x", "x", null }));
+        assertEquals("Xbc", StringUtils.replaceEach(text, new String[] { "", 
null, "a", "b" }, new String[] { "x", "x", "X", null }));
+    }
+
+    @Test
+    void testReplaceEachOverlappingMatches() {
+        // The first replacement consumes a previously found match of "bc"; 
the later one must still be found.
+        assertEquals("XcY", StringUtils.replaceEach("abcbc", new String[] { 
"ab", "bc" }, new String[] { "X", "Y" }));
+        assertEquals("XX", StringUtils.replaceEach("abab", new String[] { 
"ab", "b" }, new String[] { "X", "Y" }));
+    }
+
+    /**
+     * Preserves unchanged ranges and individual UTF-16 code units in single 
and repeated replacement passes.
+     *
+     * @param value the text repeated between replacement tokens.
+     */
+    @ParameterizedTest
+    @ValueSource(strings = { "", "plain", "\u4e2d\u6587", "\ud83d\ude00", 
"\ud83d", "\ude00" })
+    void testReplaceEachPreservesUnchangedRanges(final String value) {
+        final String padding = StringUtils.repeat(value, 128);
+        final String text = padding + "<a>" + padding + "<b>" + padding;
+        final String[] searches = { "<a>", "<b>" };
+        final String[] replacements = { "<b>", "X" };
+        assertEquals(padding + "<b>" + padding + "X" + padding, 
StringUtils.replaceEach(text, searches, replacements));
+        assertEquals(padding + "X" + padding + "X" + padding, 
StringUtils.replaceEachRepeatedly(text, searches, replacements));
+    }
+
+    @Test
+    void testReplaceEachSamePositionUsesSearchOrder() {
+        assertEquals("XbXb", StringUtils.replaceEach("abab", new String[] { 
"a", "ab" }, new String[] { "X", "Y" }));
+        assertEquals("YY", StringUtils.replaceEach("abab", new String[] { 
"ab", "a" }, new String[] { "Y", "X" }));
+    }
+
     @Test
     void testReplaceFirst_StringStringString() {
         assertNull(StringUtils.replaceFirst(null, "", ""));

Reply via email to