From 493f75e89255f719c3163fd686ef5244f54cdd18 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Fri, 18 Aug 2023 11:40:19 +0200 Subject: [PATCH] Optimize whitespace checks in StringUtils (as far as possible on JDK 8) Closes gh-31067 --- .../org/springframework/util/StringUtils.java | 21 ++++++++++--------- 1 file changed, 11 insertions(+), 10 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 e803a05db2d2..96290a3cea61 100644 --- a/spring-core/src/main/java/org/springframework/util/StringUtils.java +++ b/spring-core/src/main/java/org/springframework/util/StringUtils.java @@ -247,26 +247,26 @@ public static String trimWhitespace(String str) { /** * Trim all whitespace from the given {@code CharSequence}: * leading, trailing, and in between characters. - * @param text the {@code CharSequence} to check + * @param str the {@code CharSequence} to check * @return the trimmed {@code CharSequence} * @since 5.3.22 * @see #trimAllWhitespace(String) * @see java.lang.Character#isWhitespace */ - public static CharSequence trimAllWhitespace(CharSequence text) { - if (!hasLength(text)) { - return text; + public static CharSequence trimAllWhitespace(CharSequence str) { + if (!hasLength(str)) { + return str; } - int len = text.length(); - StringBuilder sb = new StringBuilder(text.length()); + int len = str.length(); + StringBuilder sb = new StringBuilder(str.length()); for (int i = 0; i < len; i++) { - char c = text.charAt(i); + char c = str.charAt(i); if (!Character.isWhitespace(c)) { sb.append(c); } } - return sb.toString(); + return sb; } /** @@ -278,9 +278,10 @@ public static CharSequence trimAllWhitespace(CharSequence text) { * @see java.lang.Character#isWhitespace */ public static String trimAllWhitespace(String str) { - if (str == null) { - return null; + if (!hasLength(str)) { + return str; } + return trimAllWhitespace((CharSequence) str).toString(); }