Skip to content
This repository was archived by the owner on Oct 31, 2024. It is now read-only.

Commit 8f007ca

Browse files
authored
Merge pull request #46 from gatling/string-escape-helper-optim
Reduce StringEscapeHelper escape and unescape allocations
2 parents 672c528 + 45a207f commit 8f007ca

2 files changed

Lines changed: 19 additions & 2 deletions

File tree

jmespath-core/src/main/java/io/burt/jmespath/util/StringEscapeHelper.java

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ public String unescape(String str) {
4343
int slashIndex = str.indexOf('\\');
4444
if (slashIndex > -1) {
4545
int offset = 0;
46-
StringBuilder unescaped = new StringBuilder();
46+
StringBuilder unescaped = new StringBuilder(str.length() - 1);
4747
while (slashIndex > -1) {
4848
char c = str.charAt(slashIndex + 1);
4949
char r = (c < unescapeMap.length) ? unescapeMap[c] : NO_REPLACEMENT;
@@ -68,18 +68,24 @@ public String unescape(String str) {
6868
}
6969

7070
public String escape(String str) {
71-
StringBuilder escaped = new StringBuilder();
71+
StringBuilder escaped = null;
7272
int offset = 0;
7373
for (int i = 0; i < str.length(); i++) {
7474
char c = str.charAt(i);
7575
char r = (c < escapeMap.length) ? escapeMap[c] : NO_REPLACEMENT;
7676
if (r != NO_REPLACEMENT) {
77+
if (escaped == null) {
78+
escaped = new StringBuilder(str.length() + 1);
79+
}
7780
escaped.append(str, offset, i);
7881
escaped.append('\\');
7982
escaped.append(r);
8083
offset = i + 1;
8184
}
8285
}
86+
if (escaped == null) {
87+
return str;
88+
}
8389
if (offset < str.length()) {
8490
escaped.append(str, offset, str.length());
8591
}

jmespath-core/src/test/java/io/burt/jmespath/util/StringEscapeHelperTest.java

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,4 +52,15 @@ public void specialCharsAreEscaped() {
5252
String escaped = escapeHelper.escape("\thello\nworld!");
5353
assertThat(escaped, is("\\thello\\nworld\\x"));
5454
}
55+
56+
@Test
57+
public void stringWithoutSpecialCharsIsNotModified() {
58+
StringEscapeHelper escapeHelper = new StringEscapeHelper(
59+
'n', '\n',
60+
't', '\t',
61+
'x', '!'
62+
);
63+
String escaped = escapeHelper.escape("hello world");
64+
assertThat(escaped, is("hello world"));
65+
}
5566
}

0 commit comments

Comments
 (0)