1.问题
今天在知乎看到一个很有意思的问题,记录下
private String testStr = "This is a test string";
private char[] testChar = { 'a', 'b', 'c', 'd' };
// 代码块1
for (int i = 0; i < testStr.length(); i++) {
for (int j = 0; j < testChar.length; j++) {
if (testStr.charAt(i) == testChar[j]) {
return true;
}
}
}
// 代码块2
for (int i = 0; i < testStr.length(); i++) {
for (int j = 0; j < testChar.length; j++) {
if (testStr.charAt(i) == testChar[j]) {
return true;
}
}
}
2.性能测试
import org.openjdk.jmh.annotations.*;
import java.util.concurrent.TimeUnit;
@State(Scope.Benchmark)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public class CharComparisonBenchmark {
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder().include(For2Test.class.getSimpleName()).warmupIterations(1).measurementIterations(1).forks(1).build();
new Runner(opt).run();
}
private static final String testStr = "This is a test string";
private static final char[] testChar = { 'a', 'b', 'c', 'd' };
@Benchmark
public boolean testCharComparison1() {
for (int i = 0; i < testStr.length(); i++) {
for (int j = 0; j < testChar.length; j++) {
if (testStr.charAt(i) == testChar[j]) {
return true;
}
}
}
return false;
}
@Benchmark
public boolean testCharComparison2() {
for (int i = 0; i < testStr.length(); i++) {
for (int j = 0; j < testChar.length; j++) {
if (testStr.charAt(i) == testChar[j]) {
return true;
}
}
}
return false;
}
}
测试结果基本符合预期,当时完备的测试数据量应该是随机的,且字符数较多,有兴趣的同学可以继续研究下