下面2 段代码性能上哪个更优?

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;
    }
}

测试结果基本符合预期,当时完备的测试数据量应该是随机的,且字符数较多,有兴趣的同学可以继续研究下
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值