美文网首页
java中数组多种遍历求和的效率分析

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

作者: 眼若繁星丶 | 来源:发表于2021-02-01 12:50 被阅读0次

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

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

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

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

测试代码如下:

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

相关文章

网友评论

      本文标题:java中数组多种遍历求和的效率分析

      本文链接:https://www.haomeiwen.com/subject/lxmjtltx.html