Skip to content

Commit 0499acf

Browse files
author
Brock Noland
committed
Improve performance of trim 25x on large strings
Change-Id: I8d6022d9bf05275ac358ee735882682a1fc1b0d0
1 parent 56eafdb commit 0499acf

File tree

2 files changed

+18
-1
lines changed
  • src
    • main/java/com/github/vertical_blank/sqlformatter/core/util
    • test/groovy/com/github/vertical_blank/sqlformatter/core/util

2 files changed

+18
-1
lines changed

src/main/java/com/github/vertical_blank/sqlformatter/core/util/Util.java

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,12 @@ public static <T> List<T> nullToEmpty(List<T> ts) {
1919
}
2020

2121
public static String trimEnd(String s) {
22-
return s.replaceAll("[ |\\n|\\r]*$", "");
22+
int endIndex = s.length();
23+
char[] chars = s.toCharArray();
24+
while(endIndex > 0 && (chars[endIndex - 1] == ' ' || chars[endIndex - 1] == '\n' || chars[endIndex - 1] == '\r')) {
25+
endIndex--;
26+
}
27+
return new String(chars, 0, endIndex);
2328
}
2429

2530
public static String escapeRegExp(String s) {

src/test/groovy/com/github/vertical_blank/sqlformatter/core/util/UtilTest.groovy

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,5 +9,17 @@ class UtilTest {
99
def escaped = Util.escapeRegExp('[lodash](https://lodash.com/)')
1010
assert escaped == '''\\[lodash\\]\\(https://lodash\\.com/\\)'''
1111
}
12+
@Test
13+
void testTrimEnd() {
14+
assert "" == Util.trimEnd(" ");
15+
assert "" == Util.trimEnd("");
16+
assert " \r\nabc" == Util.trimEnd(" \r\nabc");
17+
assert " \r\nabc" == Util.trimEnd(" \r\nabc ");
18+
assert " \r\nabc" == Util.trimEnd(" \r\nabc\n");
19+
assert " \r\nabc" == Util.trimEnd(" \r\nabc\r");
20+
assert " \r\nabc" == Util.trimEnd(" \r\nabc\r\n");
21+
assert " \r\nabc" == Util.trimEnd(" \r\nabc\r\n ");
22+
assert " \r\nabc" == Util.trimEnd(" \r\nabc \r\n \n ");
23+
}
1224

1325
}

0 commit comments

Comments
 (0)