Java performance optimization - test the performance comparison and business difference between try-catch placed inside and outside the loop

Scenes

Use JMH (Java Microbenchmark Harness micro-benchmark testing framework) in Java for performance testing and optimization:

Use JMH (Java Microbenchmark Harness micro-benchmark testing framework) in Java for performance testing and optimization - Programmer Sought

Use the above method to test whether there is a performance difference between try-catch in Java and outside the loop.

Note:

Blog:
Overbearing rogue temperament blog_CSDN Blog-C#, Architecture Road, Blogger in SpringBoot

accomplish

1. Have you heard that the execution of try-catch in the loop body will be very slow?

In order to verify the above conclusion, do the following test

import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import java.util.concurrent.TimeUnit;


@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 2,time = 1,timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 5,time = 5,timeUnit = TimeUnit.SECONDS)
@Fork(1)
@State(Scope.Benchmark)
@Threads(100)
public class TryCatchVSCircleTest {

    private static final int maxSize = 10000; //测试循环次数

    public static void main(String[] args) throws RunnerException {
        //启动基准测试
        Options opt = new OptionsBuilder()
                .include(TryCatchVSCircleTest.class.getSimpleName())  //要导入的测试类
                .build();
        //执行测试
        new Runner(opt).run();
    }

    @Benchmark
    public int innerForeach(){
        int count = 0;
        for (int i = 0; i < maxSize; i++) {
            try{
                if(i == maxSize){
                    throw new Exception("exception");
                }
                count++;
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return count;
    }

    @Benchmark
    public int outerForeach(){
        int count = 0;
        try{
            for (int i = 0; i < maxSize; i++) {
                if(i == maxSize){
                    throw new Exception("exception");
                }
                count++;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
       return count;
    }
}

Test Results

Benchmark Mode Cnt Score Error Units
TryCatchVSCircleTest.innerForeach avgt 5 13528.011 ± 833.369 ns/op
TryCatchVSCircleTest.outerForeach avgt 5 13645.087 ± 565.900 ns/op

2. Conclusion

In the case of no abnormality, we get the conclusion after removing the error value:

There is almost no difference in the performance of try-catch whether it is inside the for loop or outside the for loop.

By analyzing its bytecode, we can know:

If there is no error in the code, the performance is almost unaffected, and the execution logic of the normal code is the same.

Although the performance of try-catch inside or outside the loop is similar, the business meanings of their codes are completely different.

The try-catch in the loop body can continue to execute the loop after an exception occurs; while the try-catch outside the loop

Usually the loop is terminated afterwards.

Therefore, when we decide whether try-catch should be placed inside or outside the loop, it does not depend on performance (because the performance is almost the same),

Instead, it should depend on the specific business scenario.

For example, we need to process a batch of data, and no matter which data in this set of data has a problem, it cannot affect the normal execution of other groups.

, at this point we can place the try-catch in the loop body;

And when we need to calculate the total value of a set of data, as long as there is an error in a set of data, we need to terminate the execution and throw an exception,

At this point we need to place the try-catch outside the loop for execution.

Guess you like

Origin blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/131751387