首页 > 其他分享 >ParallelStreamPerformance2

ParallelStreamPerformance2

时间:2024-09-14 14:55:50浏览次数:11  
标签:12 数据类型 System long Integer ParallelStreamPerformance2 public


package com.shrimpking.t4;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Shrimpking
 * @create 2024/9/12 12:09
 */
public interface Test
{
    void test();
}
package com.shrimpking.t4;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Shrimpking
 * @create 2024/9/12 12:10
 */
public class Tester
{
    public static long runTest(Test t){
        long start = System.currentTimeMillis();
        t.test();
        long end = System.currentTimeMillis();
        return end - start;
    }
}
package com.shrimpking.t4;

import java.util.Arrays;
import java.util.stream.IntStream;
import java.util.stream.Stream;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Shrimpking
 * @create 2024/9/12 13:09
 */
public class ParallelStreamPerformance2
{
    public static void main(String[] args)
    {
        Integer[] inArray = new Integer[10000];
        for (int i = 1; i <= 10000; i++)
        {
            inArray[i-1] = i;
        }

        int[] iArray = new int[10000];
        for (int i = 1; i <= 10000; i++)
        {
            iArray[i-1] = i;
        }

        //并行流
        Stream<Integer> stream1 = Arrays.stream(inArray).parallel();
        IntStream stream2 = Arrays.stream(iArray).parallel();

        long time1 = Tester.runTest(() -> stream1.reduce(0,Integer::sum));
        System.out.println("封装类对象并行流花费时间:" + time1);

        long time2 = Tester.runTest(() -> stream2.reduce(0,Integer::sum));
        System.out.println("基本数据类型并行流花费时间:" + time2);

        //基本数据类型的流在进行累加操作时,其性能明显高于封装类对象。
        //原因很简单,在进行计算时,封装类对象要拆箱为基本数据类型才能求和,
        //损耗较大,性能就差。因此,对整数或浮点数序列进行操作时,
        //尽量选择基本数据类型,不要采用封装类型


    }
}

标签:12,数据类型,System,long,Integer,ParallelStreamPerformance2,public
From: https://blog.51cto.com/u_15356972/12016819

相关文章