Skip to content

Commit 5a1d7f9

Browse files
hasheniukjhoeller
authored andcommitted
Improve performance of StringUtils#trimWhitespace
Issue: SPR-16766 (cherry picked from commit 6545cab)
1 parent b55f69d commit 5a1d7f9

File tree

1 file changed

+10
-6
lines changed

1 file changed

+10
-6
lines changed

spring-core/src/main/java/org/springframework/util/StringUtils.java

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -209,14 +209,18 @@ public static String trimWhitespace(String str) {
209209
return str;
210210
}
211211

212-
StringBuilder sb = new StringBuilder(str);
213-
while (sb.length() > 0 && Character.isWhitespace(sb.charAt(0))) {
214-
sb.deleteCharAt(0);
212+
int beginIndex = 0;
213+
int endIndex = str.length() - 1;
214+
215+
while (beginIndex <= endIndex && Character.isWhitespace(str.charAt(beginIndex))) {
216+
beginIndex++;
215217
}
216-
while (sb.length() > 0 && Character.isWhitespace(sb.charAt(sb.length() - 1))) {
217-
sb.deleteCharAt(sb.length() - 1);
218+
219+
while (endIndex > beginIndex && Character.isWhitespace(str.charAt(endIndex))) {
220+
endIndex--;
218221
}
219-
return sb.toString();
222+
223+
return str.substring(beginIndex, endIndex + 1);
220224
}
221225

222226
/**

0 commit comments

Comments
 (0)