Skip to content

Commit

Permalink
Merge pull request #46 from gatling/string-escape-helper-optim
Browse files Browse the repository at this point in the history
Reduce StringEscapeHelper escape and unescape allocations
  • Loading branch information
iconara committed Jun 7, 2019
2 parents 672c528 + 45a207f commit 8f007ca
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public String unescape(String str) {
int slashIndex = str.indexOf('\\');
if (slashIndex > -1) {
int offset = 0;
StringBuilder unescaped = new StringBuilder();
StringBuilder unescaped = new StringBuilder(str.length() - 1);
while (slashIndex > -1) {
char c = str.charAt(slashIndex + 1);
char r = (c < unescapeMap.length) ? unescapeMap[c] : NO_REPLACEMENT;
Expand All @@ -68,18 +68,24 @@ public String unescape(String str) {
}

public String escape(String str) {
StringBuilder escaped = new StringBuilder();
StringBuilder escaped = null;
int offset = 0;
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
char r = (c < escapeMap.length) ? escapeMap[c] : NO_REPLACEMENT;
if (r != NO_REPLACEMENT) {
if (escaped == null) {
escaped = new StringBuilder(str.length() + 1);
}
escaped.append(str, offset, i);
escaped.append('\\');
escaped.append(r);
offset = i + 1;
}
}
if (escaped == null) {
return str;
}
if (offset < str.length()) {
escaped.append(str, offset, str.length());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,4 +52,15 @@ public void specialCharsAreEscaped() {
String escaped = escapeHelper.escape("\thello\nworld!");
assertThat(escaped, is("\\thello\\nworld\\x"));
}

@Test
public void stringWithoutSpecialCharsIsNotModified() {
StringEscapeHelper escapeHelper = new StringEscapeHelper(
'n', '\n',
't', '\t',
'x', '!'
);
String escaped = escapeHelper.escape("hello world");
assertThat(escaped, is("hello world"));
}
}

0 comments on commit 8f007ca

Please sign in to comment.