Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimize StringUtils trimLeading/Trailing methods #25810

Merged
merged 1 commit into from Sep 25, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
32 changes: 16 additions & 16 deletions spring-core/src/main/java/org/springframework/util/StringUtils.java
Expand Up @@ -271,11 +271,11 @@ public static String trimLeadingWhitespace(String str) {
return str;
}

StringBuilder sb = new StringBuilder(str);
while (sb.length() > 0 && Character.isWhitespace(sb.charAt(0))) {
sb.deleteCharAt(0);
int beginIdx = 0;
while (beginIdx < str.length() && Character.isWhitespace(str.charAt(beginIdx))) {
beginIdx++;
}
return sb.toString();
return str.substring(beginIdx);
}

/**
Expand All @@ -289,11 +289,11 @@ public static String trimTrailingWhitespace(String str) {
return str;
}

StringBuilder sb = new StringBuilder(str);
while (sb.length() > 0 && Character.isWhitespace(sb.charAt(sb.length() - 1))) {
sb.deleteCharAt(sb.length() - 1);
int endIdx = str.length() - 1;
while (endIdx >= 0 && Character.isWhitespace(str.charAt(endIdx))) {
endIdx--;
}
return sb.toString();
return str.substring(0, endIdx + 1);
}

/**
Expand All @@ -307,11 +307,11 @@ public static String trimLeadingCharacter(String str, char leadingCharacter) {
return str;
}

StringBuilder sb = new StringBuilder(str);
while (sb.length() > 0 && sb.charAt(0) == leadingCharacter) {
sb.deleteCharAt(0);
int beginIdx = 0;
while (beginIdx < str.length() && leadingCharacter == str.charAt(beginIdx)) {
beginIdx++;
}
return sb.toString();
return str.substring(beginIdx);
}

/**
Expand All @@ -325,11 +325,11 @@ public static String trimTrailingCharacter(String str, char trailingCharacter) {
return str;
}

StringBuilder sb = new StringBuilder(str);
while (sb.length() > 0 && sb.charAt(sb.length() - 1) == trailingCharacter) {
sb.deleteCharAt(sb.length() - 1);
int endIdx = str.length() - 1;
while (endIdx >= 0 && trailingCharacter == str.charAt(endIdx)) {
endIdx--;
}
return sb.toString();
return str.substring(0, endIdx + 1);
}

/**
Expand Down