java流式api,Java 8 中流式API性能基准测试
測試代碼
package hello.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.Arrays;
import java.util.concurrent.TimeUnit;
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@State(Scope.Thread)
public class BenchmarkTest {
public static final String[] BRAND_ARRAY = {"iphone", "huawei", "xiaomi", "samsung", "vivo", "bbk", "oppo", "meizu", "sony", "xperia", "htc", "oneplus", "smartisan", "lenovo", "gionee", "nubia", "letv", "vertu"};
private static final String bidRequestModel = "oneplus";
@Benchmark
public static String findBidrequstBrandByStream() {
final String lowBidRequestModel = bidRequestModel.toLowerCase();
return Arrays.stream(BRAND_ARRAY).filter(x -> lowBidRequestModel.contains(x)).findAny().get();
}
@Benchmark
public static String findBidrequstBrandByParallelStream() {
final String lowBidRequestModel = bidRequestModel.toLowerCase();
return Arrays.stream(BRAND_ARRAY).parallel().filter(x -> lowBidRequestModel.contains(x)).findAny().get();
}
@Benchmark
public static String findBidrequstBrandByArray() {
final String lowBidRequestModel = bidRequestModel.toLowerCase();
for (String e : BRAND_ARRAY) {
if (lowBidRequestModel.contains(e)) {
return e;
}
}
return "";
}
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(BenchmarkTest.class.getSimpleName())
.forks(1)
.warmupIterations(5)
.measurementIterations(5)
.build();
new Runner(opt).run();
}
}
結果
Benchmark Mode Cnt Score Error Units
BenchmarkTest.findBidrequstBrandByArray thrpt 5 11206.177 ± 1438.816 ops/ms
BenchmarkTest.findBidrequstBrandByParallelStream thrpt 5 206.097 ± 95.776 ops/ms
BenchmarkTest.findBidrequstBrandByStream thrpt 5 4838.695 ± 368.454 ops/ms
總結
對性能敏感的程序, 建議還是用回傳統的for循環
并行流并不一定會比順序流快
java 8 的流式api, 一般情況下比不上傳統的 for 循環
總結
以上是生活随笔為你收集整理的java流式api,Java 8 中流式API性能基准测试的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: windows c语言 http htt
- 下一篇: 算法训练 数的划分 动态规划