J'étais curieux et j'ai décidé de le comparer avec JMH ; voici ce que j'ai trouvé :
@State(Scope.Benchmark)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 5, time = 500, timeUnit = TimeUnit.MILLISECONDS)
@Measurement(iterations = 10, time = 500, timeUnit = TimeUnit.MILLISECONDS)
@Fork(3)
public class MyBenchmark {
@Param({"ASDQWE!&"})
private String test;
private static final Pattern PATTERN = Pattern.compile("[A-Z!$&?]*");
public static void main(String[] args) throws Exception {
org.openjdk.jmh.Main.main(args);
}
@Benchmark
public boolean oldMethod() {
for (int i = 0; i < test.length(); i++) {
int c = test.charAt(i);
if (c >= 65 && c <= 90) {
continue;
}
switch (test.charAt(i)) {
case 33:
case 36:
case 38:
case 63:
break;
default:
return false;
}
}
return true;
}
@Benchmark
public boolean newMethod() {
return PATTERN.matcher(test).matches();
}
}
Et ses résultats :
Benchmark (test) Mode Cnt Score Error Units
MyBenchmark.newMethod ASDQWE!& avgt 30 55.848 ± 1.275 ns/op
MyBenchmark.oldMethod ASDQWE!& avgt 30 14.586 ± 0.034 ns/op
Même en compilant un modèle, il est clair qu'en itérant sur le fichier String
sera plus rapide, mais il est définitivement plus lisible lorsqu'on utilise une expression régulière.