java中数组多种遍历求和的效率分析

本文最后更新于:2021年3月27日 晚上

java中数组多种遍历求和的效率分析

int型数组的遍历求和效率分析

  • 转换成流的形式,再求和。IntStream.of(a).sum();
  • 另一种转换流求和的方式,Arrays.stream(a).sum();
  • 普通for loop 求和:for i
  • 增强for loop 求和:for-each

测试方法使用的是 System.nanoTime() 求出求和段的运行时间,单位为纳秒(10^-9 s)

测试代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class Solution {
public static void main(String[] args) {
int[] a = new int[100];
for (int i = 0; i < 100; i++) {
a[i] = i + 1;
}
long l1, l2;
int sum1, sum2, sum3 = 0, sum4 = 0;

l1 = System.nanoTime();
sum1 = IntStream.of(a).sum();
l2 = System.nanoTime();
System.out.print("IntStream.of(a).sum(): ");
System.out.println(sum1);
System.out.println(l2 - l1);

l1 = System.nanoTime();
sum2 = Arrays.stream(a).sum();
l2 = System.nanoTime();
System.out.print("Arrays.stream(a).sum(): ");
System.out.println(sum2);
System.out.println(l2 - l1);

l1 = System.nanoTime();
for (int i = 0; i < a.length; i++) {
sum3 += a[i];
}
l2 = System.nanoTime();
System.out.print("for loop: ");
System.out.println(sum3);
System.out.println(l2 - l1);

l1 = System.nanoTime();
for (int i : a) {
sum4 += i;
}
l2 = System.nanoTime();
System.out.print("iterator loop: ");
System.out.println(sum4);
System.out.println(l2 - l1);
}
}

IntStream.of(a).sum(): 5050
24215600
Arrays.stream(a).sum(): 5050
184000
for loop: 5050
1600
iterator loop: 5050
1800

求和结果都是正确的。所以根据最后求和速度进行排序,效率从低到高:

IntStream.of(A).sum() < Arrays.stream(A).sum() < iterator loop < for loop