From 5a1d7f9c4bd9ffcb8d7caa506972ca7a392d2604 Mon Sep 17 00:00:00 2001 From: Oleksandr Hasheniuk Date: Tue, 24 Apr 2018 21:05:58 +0200 Subject: [PATCH] Improve performance of StringUtils#trimWhitespace Issue: SPR-16766 (cherry picked from commit 6545cab) --- .../org/springframework/util/StringUtils.java | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 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 2df8e9c645c..b34e8a7e07a 100644 --- a/spring-core/src/main/java/org/springframework/util/StringUtils.java +++ b/spring-core/src/main/java/org/springframework/util/StringUtils.java @@ -209,14 +209,18 @@ public abstract class StringUtils { return str; } - StringBuilder sb = new StringBuilder(str); - while (sb.length() > 0 && Character.isWhitespace(sb.charAt(0))) { - sb.deleteCharAt(0); + int beginIndex = 0; + int endIndex = str.length() - 1; + + while (beginIndex <= endIndex && Character.isWhitespace(str.charAt(beginIndex))) { + beginIndex++; } - while (sb.length() > 0 && Character.isWhitespace(sb.charAt(sb.length() - 1))) { - sb.deleteCharAt(sb.length() - 1); + + while (endIndex > beginIndex && Character.isWhitespace(str.charAt(endIndex))) { + endIndex--; } - return sb.toString(); + + return str.substring(beginIndex, endIndex + 1); } /**