Skip to content

Commit

Permalink
Optimize whitespace checks in StringUtils (as far as possible on JDK 8)
Browse files Browse the repository at this point in the history
Closes gh-31067
  • Loading branch information
jhoeller committed Aug 18, 2023
1 parent df066d8 commit 493f75e
Showing 1 changed file with 11 additions and 10 deletions.
21 changes: 11 additions & 10 deletions spring-core/src/main/java/org/springframework/util/StringUtils.java
Expand Up @@ -247,26 +247,26 @@ public static String trimWhitespace(String str) {
/**
* Trim <em>all</em> 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;
}

/**
Expand All @@ -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();
}

Expand Down

0 comments on commit 493f75e

Please sign in to comment.