测试代码
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 循环