-3

我发现在 arraylist 中存在的 10000000 个随机数中查找最大元素的执行时间在流中更多,在 for 循环中更少。为什么会这样?如果使用流的执行时间比 for 循环慢,那么使用它有什么好处图像显示执行时间

Exection time/output :-

Max ele:- 0.9999999991234259
Time taken for iteration: 86
Max ele:- 0.9999999991234259
Time taken for stream: 152 

Code for the above operation 

 ArrayList<Double> randomList = new ArrayList<>();
        for(int i=0;i<10000000;i++){
            randomList.add(Math.random());
        }

        // Find max element with iteration

        long start = time();
        double max = Double.MIN_VALUE;
        for(double d : randomList){
            /*if(d > max){
                max = d;
            }*/
            max = Math.max(d,max);
        }
        System.out.println(max);
        long end = time();
        System.out.println("Time taken for iteration: "+(end-start));

        //  Find max with stream
        long start2 = time();
        System.out.println(randomList.stream().max(Double::compare).get());
        long end2 = time();
        System.out.println("Time taken for stream: "+(end2-start2));
4

0 回答 0