Created
November 21, 2017 19:45
-
-
Save tlehman/38a198d5923f382e438a5d38e75225af to your computer and use it in GitHub Desktop.
Comparing run times of computing a max int using a loop, Java 8 streams and parallel streams
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package com.tobilehman.benchmarks; | |
| import java.util.LinkedList; | |
| import java.util.List; | |
| import java.util.Random; | |
| public class StreamMax { | |
| public static void main(String args[]) { | |
| StreamMax sm = new StreamMax(10_000_000); | |
| Long then,now; | |
| Integer max; | |
| then = System.currentTimeMillis(); | |
| max = sm.maxByLoop(); | |
| now = System.currentTimeMillis(); | |
| display(max, now-then); | |
| then = System.currentTimeMillis(); | |
| max = sm.maxByStream(); | |
| now = System.currentTimeMillis(); | |
| display(max, now-then); | |
| then = System.currentTimeMillis(); | |
| max = sm.maxByParallelStream(); | |
| now = System.currentTimeMillis(); | |
| display(max, now-then); | |
| } | |
| private static void display(Integer max, Long interval) { | |
| System.out.printf("Found max = %d in %d milliseconds\n", max, interval); | |
| } | |
| private final int size; | |
| private final List<Integer> numbers; | |
| private void initNumbers() { | |
| if(numbers.size() == 0) { | |
| Random r = new Random(); | |
| for (int i = 0; i < size; i++) { | |
| numbers.add(r.nextInt()); | |
| } | |
| } | |
| } | |
| public StreamMax(int size) { | |
| this.size = size; | |
| this.numbers = new LinkedList<Integer>(); | |
| initNumbers(); | |
| } | |
| public Integer maxByStream() { | |
| return numbers.stream().max(Integer::compareTo).get(); | |
| } | |
| public Integer maxByParallelStream() { | |
| return numbers.parallelStream().max(Integer::compareTo).get(); | |
| } | |
| public Integer maxByLoop() { | |
| Integer max = Integer.MIN_VALUE; | |
| for (Integer number : numbers) { | |
| if(number > max) { | |
| max = number; | |
| } | |
| } | |
| return max; | |
| } | |
| } |
Author
Author
Tweaking size a bit doesn't change the fact that loops are reliably faster than streams, at least for this problem.
Found max = 2147482884 in 246 milliseconds
Found max = 2147482884 in 209 milliseconds
Found max = 2147482884 in 453 milliseconds
Output from Intel core2 duo.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Found max = 2147483534 in 111 milliseconds
Found max = 2147483534 in 256 milliseconds
Found max = 2147483534 in 169 milliseconds