ฉันยังใหม่กับ Java 8 ฉันยังไม่รู้ API ในเชิงลึก แต่ฉันได้ทำเกณฑ์มาตรฐานอย่างไม่เป็นทางการเพื่อเปรียบเทียบประสิทธิภาพของ Streams API ใหม่กับคอลเลกชันเก่าที่ดี
การทดสอบประกอบด้วยในการกรองรายการIntegerและจำนวนคู่แต่ละคำนวณรากและเก็บไว้ในผลของListDouble
นี่คือรหัส:
    public static void main(String[] args) {
        //Calculating square root of even numbers from 1 to N       
        int min = 1;
        int max = 1000000;
        List<Integer> sourceList = new ArrayList<>();
        for (int i = min; i < max; i++) {
            sourceList.add(i);
        }
        List<Double> result = new LinkedList<>();
        //Collections approach
        long t0 = System.nanoTime();
        long elapsed = 0;
        for (Integer i : sourceList) {
            if(i % 2 == 0){
                result.add(Math.sqrt(i));
            }
        }
        elapsed = System.nanoTime() - t0;       
        System.out.printf("Collections: Elapsed time:\t %d ns \t(%f seconds)%n", elapsed, elapsed / Math.pow(10, 9));
        //Stream approach
        Stream<Integer> stream = sourceList.stream();       
        t0 = System.nanoTime();
        result = stream.filter(i -> i%2 == 0).map(i -> Math.sqrt(i)).collect(Collectors.toList());
        elapsed = System.nanoTime() - t0;       
        System.out.printf("Streams: Elapsed time:\t\t %d ns \t(%f seconds)%n", elapsed, elapsed / Math.pow(10, 9));
        //Parallel stream approach
        stream = sourceList.stream().parallel();        
        t0 = System.nanoTime();
        result = stream.filter(i -> i%2 == 0).map(i -> Math.sqrt(i)).collect(Collectors.toList());
        elapsed = System.nanoTime() - t0;       
        System.out.printf("Parallel streams: Elapsed time:\t %d ns \t(%f seconds)%n", elapsed, elapsed / Math.pow(10, 9));      
    }.และนี่คือผลลัพธ์สำหรับเครื่องดูอัลคอร์:
    Collections: Elapsed time:        94338247 ns   (0,094338 seconds)
    Streams: Elapsed time:           201112924 ns   (0,201113 seconds)
    Parallel streams: Elapsed time:  357243629 ns   (0,357244 seconds)สำหรับการทดสอบนี้โดยเฉพาะสตรีมจะช้ากว่าคอลเล็กชั่นประมาณสองเท่าและการขนานกันก็ไม่ได้ช่วยอะไร
คำถาม:
- การทดสอบนี้ยุติธรรมหรือไม่ ฉันทำผิดพลาดหรือไม่?
- สตรีมช้ากว่าคอลเล็กชันหรือไม่ มีใครทำมาตรฐานอย่างเป็นทางการที่ดีเกี่ยวกับเรื่องนี้?
- ฉันควรพยายามหาวิธีใด
อัปเดตผลลัพธ์
ฉันรันการทดสอบ 1k ครั้งหลังจากการอุ่นเครื่อง JVM (การทำซ้ำ 1k) ตามคำแนะนำของ @pveentjer:
    Collections: Average time:      206884437,000000 ns     (0,206884 seconds)
    Streams: Average time:           98366725,000000 ns     (0,098367 seconds)
    Parallel streams: Average time: 167703705,000000 ns     (0,167704 seconds)ในกรณีนี้สตรีมจะมีประสิทธิภาพมากกว่า ฉันสงสัยว่าจะพบสิ่งใดในแอปที่ฟังก์ชั่นการกรองถูกเรียกเพียงครั้งเดียวหรือสองครั้งในช่วงรันไทม์
toListควรทำงานแบบขนานแม้ว่าจะรวบรวมไปยังรายการที่ไม่ปลอดภัยเนื่องจากเธรดที่แตกต่างกันจะรวบรวมไปยังรายการกลางที่ จำกัด เธรดก่อนที่จะรวมเข้าด้วยกัน
                
IntStreamแทนหรือไม่?