我正在玩java 1.8.我读到新的集合api工作得更快,因为它在并行化的数据结构上运行操作.
我想看看这个efford.所以我写了下面的代码:
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);
}
Run Code Online (Sandbox Code Playgroud)
我的处理器:i7-2600 CPU
使用"并行"方式的结果:以纳秒为单位的时间:74836825
使用顺序方式的结果:以纳秒为单位的时间:45071315
大家可以解释一下这个结果吗?建立这种威胁的开销是否很高?我有点困惑请帮帮我:-)