The benchmarking tool JMH can be used to compare the performance of Java functions. Benchmarking two functions that sum arrays, it was found that the Java streaming function (sumArray2) is superior to the native loop function (sumArray1) because it takes advantage of parallelization and thus performs better on large arrays.
Performance is a key consideration when writing Java code. By benchmarking different functions, we can determine which function performs best in a specific scenario.
The Java Microbenchmark Suite (JMH) is a popular library for benchmarking in Java. It provides an easy-to-use API to create benchmarks and measure execution times.
Let’s compare two functions that sum elements on an array:
// 方法 1:原生循环 public static int sumArray1(int[] arr) { int sum = 0; for (int i = 0; i < arr.length; i++) { sum += arr[i]; } return sum; } // 方法 2:Java 流 public static int sumArray2(int[] arr) { return Arrays.stream(arr).sum(); }
Use JMH Setting up a benchmark is very simple. The following is an example of JMH configuration code:
@BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public class SumArrayBenchmark { @Benchmark public int sumArray1() { int[] arr = new int[10000]; // 填充数组 return sumArray1(arr); } @Benchmark public int sumArray2() { int[] arr = new int[10000]; // 填充数组 return sumArray2(arr); } }
To run the JMH benchmark, use the following command:
mvn clean install java -jar target/benchmarks.jar
This command will print the benchmark The results show the execution time of each function.
In the above example, the performance of Java stream function sumArray2
is better than the native loop function sumArray1
. This is because Java streams take advantage of parallelization, and the performance benefits are even more pronounced especially with large arrays.
By using JMH for benchmarking, we can easily compare the performance of Java functions and determine which function is most effective in a specific scenario.
The above is the detailed content of Benchmark-based comparison of Java functions. For more information, please follow other related articles on the PHP Chinese website!