Home > database >  Why is generating integer with IntStream slower then conventional way?
Why is generating integer with IntStream slower then conventional way?

Time:08-13

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();
    }

}

CodePudding user response:

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.

  •  Tags:  
  • java
  • Related