简体   繁体   中英

Why is generating integer with IntStream slower then conventional way?

I generate int numbers with and without IntSteam, surprising to me is the fact that on my machine my code runs slower with IntStream. Can someone explain why an IntStream is slower and why we need it at all although it comesup with perfomance penalty?

import java.util.Random;
import java.util.stream.IntStream;

public class Main {

    private static Random r = new Random();
    private static int sum;
    private static int branchDirection = 500000;
    private final static LIMIT = 1000000;
    
    public static void main(String[] args) {
//      int[] randomValues= getRandomValuesWithIntStream(); // This is slower
        int[] randomValues = getRandomValuesAsUsual(); // Than this
        
        Arrays.sort(randomValues);
        
        long start = System.nanoTime();
        
        for(int i = 0;i<randomValues.length; i++) {
            if (randomValues[i] >branchDirection) {
                sum += randomValues[i];
            }
        }
        
        System.out.println("Elapsed Time: "+ (System.nanoTime()-start));
    }
    
    private static int[] getRandomValuesAsUsual() {
        int[] randomValues = new int[LIMIT];
        for(int i = 0;i<randomValues.length; i++) {
            randomValues[i] = r.nextInt();
        }
        return randomValues;
    }
    private static int[] getRandomValuesWithIntStream() {
        return IntStream.generate(r::nextInt).limit(LIMIT).toArray();
    }

}

Using streams with small amounts of input may take longer than conventional code. This fact has been covered extensively on Stack Exchange and in the Java community (articles, blogs, etc).

Streams were invented for convenience, for use in writing code in a functional style. Such code can be more concise and clear than conventional code. And may be less prone to programmer errors.

For large amounts of input, streams can perform roughly equivalent to conventional code. The overhead cost of establishing the stream can be amortized over the larger number of items being processed.

If you engage parallel streams with large amounts of input, you may see much better performance than with conventional non-concurrent code, especially on a multi-core machine.


I would not hesitate to use streams. Any small cost in overhead is likely to be insignifiant in most places of most apps. Beware the trap of premature optimization . Programmers are notoriously poor at intuiting bottlenecks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM