Skip to content

Commit

Permalink
Merge pull request #43 from vkostyukov/vk/faster-encode
Browse files Browse the repository at this point in the history
Optimize UrlCodec.encode
  • Loading branch information
xiangyao1989 committed May 16, 2019
2 parents b4f6afb + ced9b0d commit 1dcbd06
Showing 1 changed file with 26 additions and 10 deletions.
36 changes: 26 additions & 10 deletions src/main/java/com/twitter/joauth/UrlCodec.java
Original file line number Diff line number Diff line change
Expand Up @@ -56,24 +56,37 @@ public static String encode(String s) {
}

StringBuilder sb = null;
int j = 0;

// scan through to see where we have to start % encoding, if at all
int startingIndex = 0;
boolean hasReservedChars = false;
while (j < s.length()) {
if (!isUnreserved(s.charAt(j))) {
startingIndex = j;
break;
} else {
j++;
}
}

// scan through to see where we have to start % encoding, if at all
while (startingIndex < s.length() && !hasReservedChars) {
if (!isUnreserved(s.charAt(startingIndex))) {
hasReservedChars = true;
// scan through to see where we have to end % encoding, if at all
int endingIndex = startingIndex;
while (j < s.length()) {
if (!isUnreserved(s.charAt(j))) {
j += Character.charCount(s.codePointAt(j));
endingIndex = j;
} else {
startingIndex += 1;
j++;
}
}

if (hasReservedChars && startingIndex < s.length()) {
if (startingIndex < endingIndex) {
// allocate a string builder with padding for % encoding
sb = new StringBuilder(s.length() + 40);
sb.append(s.substring(0, startingIndex));
// append prefix (no encoding required)
sb.append(s, 0, startingIndex);

byte[] byteArray = s.substring(startingIndex).getBytes(UTF_8_CHARSET);
byte[] byteArray = s.substring(startingIndex, endingIndex).getBytes(UTF_8_CHARSET);
for (int i = 0; i < byteArray.length; i++) {
byte bite = byteArray[i];
if (isUnreserved(bite)) {
Expand All @@ -86,6 +99,9 @@ public static String encode(String s) {
sb.append(HEX_DIGITS[bite & 0x0F]);
}
}

// append postfix (no encoding required)
sb.append(s, endingIndex, s.length());
}

return (sb == null) ? s : sb.toString();
Expand All @@ -105,7 +121,7 @@ public static String normalize(String s) {
if (c == '%' || c == '+' || c == ',' || c == '[' || c == ']') {
if (sb == null) {
sb = new StringBuilder(s.length() + 40); //use length
sb.append(s.substring(0, i));
sb.append(s, 0, i);
}
if (c == '%') {
if (i + 3 <= length) {
Expand Down

0 comments on commit 1dcbd06

Please sign in to comment.