From 4d328d6188f4103b2162bba118c964fe7f52caf9 Mon Sep 17 00:00:00 2001 From: hengyunabc Date: Fri, 13 Jun 2014 18:36:50 +0800 Subject: [PATCH] Improve StringUtils#trimAllWhitespace Prior to this commit, StringUtils#trimAllWhitespace(String str) was unecessary slower. Using sb.deleteCharAt(index) leads to a complete copy of the char[] --- .../java/org/springframework/util/StringUtils.java | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 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 9ed12a1ea6..febb796103 100644 --- a/spring-core/src/main/java/org/springframework/util/StringUtils.java +++ b/spring-core/src/main/java/org/springframework/util/StringUtils.java @@ -216,14 +216,12 @@ public abstract class StringUtils { if (!hasLength(str)) { return str; } - StringBuilder sb = new StringBuilder(str); - int index = 0; - while (sb.length() > index) { - if (Character.isWhitespace(sb.charAt(index))) { - sb.deleteCharAt(index); - } - else { - index++; + int len = str.length(); + StringBuilder sb = new StringBuilder(str.length()); + for (int i = 0; i < len; i++) { + char c = str.charAt(i); + if (!Character.isWhitespace(c)) { + sb.append(c); } } return sb.toString();