Skip to content

Instantly share code, notes, and snippets.

@kuenishi
Created April 12, 2022 13:51
Show Gist options
  • Save kuenishi/75d7a435df20ea69c34013f9ff5515c5 to your computer and use it in GitHub Desktop.
Save kuenishi/75d7a435df20ea69c34013f9ff5515c5 to your computer and use it in GitHub Desktop.
import java.util.function.Function;
import java.lang.Long;
class Bench {
public static void main(String[] args) {
bench("noop ", (l) -> "");
bench("Long.toHexString()", (l) -> Long.toHexString(l));
bench("byteString.... ", (l) -> sfy(l));
bench("String.format(...)", (l) -> String.format("%016X", l));
}
static void bench(String name, Function<Long, String> f) {
long repeat = 10000000L;
//long repeat = 100L;
long start = java.lang.System.currentTimeMillis();
for (long i = 0; i < repeat; i++) {
f.apply(i);
}
long end = java.lang.System.currentTimeMillis();
double duration = (end - start) / 1000.0; //seconds
System.out.println(name + ":\t" + duration + " seconds\tfor " + repeat + " iteration: " + repeat / 1000.0 / duration + " Kcalls/sec");
}
static String sfy(long l) {
byte[] bytes = new byte[16];
for (int i=15; i >= 0; i--) {
if (l == 0) {
break;
}
byte rem = (byte)(l & 15L);
l = l >> 4;
bytes[i] += rem;
if (rem >= 10) {
bytes[i] += 7; // 'A' - '0' => 7
}
}
String s = new String(bytes);
// System.out.println(s);
return s;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment