Created
November 21, 2017 19:45
-
-
Save tlehman/b137af754fb97fda0ff40a6163ed209e 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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment