gpt4 book ai didi

java - Java 1.8 Collection Api 性能测试结果令人困惑

转载 作者:行者123 更新时间:2023-12-01 08:02:23 25 4
gpt4 key购买 nike

我正在玩java 1.8。我读到新的集合 api 工作得更快,因为它在数据结构上并行运行操作。

我想看看这个努力。所以我写了以下代码:

 public static void main(String[] args) {

ArrayList<SamplePerson> persons = new ArrayList<>();

for (long i = 0; i < 10000000; i++) {
persons.add(new SamplePerson(EyeColour.BLUE,20,"Max Musterman",Gender.MALE));
}

long nsBefore = System.nanoTime();


// using the new collection api - parallel way??
persons.forEach(samplePerson -> samplePerson.setAge(22));

// sequential way
for(int i = 0; i < persons.size(); i++){
persons.get(i).setAge(22);
}

long nsAfter = System.nanoTime();

long runtime = nsAfter - nsBefore;

System.out.println("Time in Nanoseconds: " + runtime);
}

我的处理器:i7-2600 CPU

使用“并行”方式的结果:时间(纳秒):74836825

使用顺序方式的结果:时间(纳秒):45071315

大家能解释一下这个结果吗?设置这种威胁的开销有那么高吗?我有点困惑请帮助我:-)

最佳答案

在对某些东西进行基准测试时,您需要考虑 JIT 预热,在这种情况下,我会让它第一次运行,并在第二次迭代中对相同的东西进行基准测试

你也没有使用你需要的parallelStream

persons.parallelStream().forEach()

关于java - Java 1.8 Collection Api 性能测试结果令人困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24312738/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com