From 275054c3f8c9d36a4202cbc0fd3ca4157d483d0e Mon Sep 17 00:00:00 2001 From: Park Sung Jun Date: Tue, 8 Oct 2024 16:57:36 +0900 Subject: [PATCH] Refactor -> StringUtils replace Optimization The += 16 used before is too abstract. -If NewPattern is longer than 16, StringBuilder must be re -permitted again. -If NewPattern is shorter than 16, you will be assigned a memory to StringBuilder. For this reason, we will request a Code that is optimized. There is also a possibility that the length of the + NewPattern will be abnormally longer, To prevent the maximum size assignment, the maximum value is set to the maximum value of the int range. --- .../java/org/springframework/util/StringUtils.java | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/spring-core/src/main/java/org/springframework/util/StringUtils.java b/spring-core/src/main/java/org/springframework/util/StringUtils.java index 86fc164c8cf9..e78efac961e9 100644 --- a/spring-core/src/main/java/org/springframework/util/StringUtils.java +++ b/spring-core/src/main/java/org/springframework/util/StringUtils.java @@ -450,17 +450,19 @@ public static String replace(String inString, String oldPattern, @Nullable Strin } int capacity = inString.length(); - if (newPattern.length() > oldPattern.length()) { - capacity += 16; + + int newPatternLen = newPattern.length(); + int oldPatternLen = oldPattern.length(); + if (newPatternLen > oldPatternLen) { + capacity += Math.min(Integer.MAX_VALUE, newPatternLen - oldPatternLen); } StringBuilder sb = new StringBuilder(capacity); int pos = 0; // our position in the old string - int patLen = oldPattern.length(); while (index >= 0) { sb.append(inString, pos, index); sb.append(newPattern); - pos = index + patLen; + pos = index + oldPatternLen; index = inString.indexOf(oldPattern, pos); }