Skip to content

Instantly share code, notes, and snippets.

@doom369
Created July 26, 2020 18:10
Show Gist options
  • Save doom369/9fc892dfb732ff1b2b9a2437ae09f1ff to your computer and use it in GitHub Desktop.
Save doom369/9fc892dfb732ff1b2b9a2437ae09f1ff to your computer and use it in GitHub Desktop.
МІкрооптимізації в Java. String equals
@BenchmarkMode(Mode.AverageTime)
@Fork(1)
@State(Scope.Thread)
@Warmup(iterations = 5, time = 1)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Measurement(iterations = 10, time = 1)
public class EqualChar {
@Param({"/", "/my/server/url"})
private String url;
@Benchmark
public boolean equalsPost() {
return url != null && url.equals("/");
}
@Benchmark
public boolean equalsPre() {
return "/".equals(url);
}
@Benchmark
public boolean equalsOptimized() {
return equalsOneChar(url);
}
private static boolean equalsOneChar(String url) {
return url != null && url.length() == 1 && url.charAt(0) == '/';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment