Skip to content

Instantly share code, notes, and snippets.

@stsypanov
Created September 11, 2020 14:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stsypanov/600692e23c215607cb5e66dd73139b38 to your computer and use it in GitHub Desktop.
Save stsypanov/600692e23c215607cb5e66dd73139b38 to your computer and use it in GitHub Desktop.
Бенчмарк для статьи на хабре
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Fork(jvmArgsAppend = {"-Xms2g", "-Xmx2g"})
public class DecodeBenchmark {
@Benchmark
public String uriDecode(Data data) {
return uriDecode(data.encoded, data.charset);
}
private static String uriDecode(String source, Charset charset) {
int length = source.length();
if (length == 0) {
return source;
}
Objects.requireNonNull(charset, "Charset must not be null");
ByteArrayOutputStream baos = new ByteArrayOutputStream(length);
boolean changed = false;
for (int i = 0; i < length; i++) {
int ch = source.charAt(i);
if (ch == '%') {
if (i + 2 < length) {
char hex1 = source.charAt(i + 1);
char hex2 = source.charAt(i + 2);
int u = Character.digit(hex1, 16);
int l = Character.digit(hex2, 16);
if (u == -1 || l == -1) {
throw new IllegalArgumentException("Invalid encoded sequence \"" + source.substring(i) + "\"");
}
baos.write((char) ((u << 4) + l));
i += 2;
changed = true;
}
else {
throw new IllegalArgumentException("Invalid encoded sequence \"" + source.substring(i) + "\"");
}
}
else {
baos.write(ch);
}
}
return (changed ? new String(baos.toByteArray(), charset) : source);
// return (changed ? baos.toString( charset) : source);
}
@State(Scope.Thread)
public static class Data {
private final Charset charset = Charset.defaultCharset();
private String encoded;
@Setup
public void setup(){
String utf8Url = "https://ru.wikipedia.org/wiki/Организация_Объединённых_Наций";
encoded = URLEncoder.encode(utf8Url, charset);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment