Last active
August 29, 2015 14:13
-
-
Save pchng/286182c5e1c914e690ec to your computer and use it in GitHub Desktop.
Simple Java 8 Stream API performance test
This file contains 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
// Test whether Stream API operations are efficiently re-ordered. | |
// LOGGER is instance of org.slf4j.Logger | |
@Test | |
public void testStreamApiOrdering() { | |
final Random rnd = new Random(); | |
final int nItems = 10_000; | |
final List<Integer> values = new ArrayList<>(nItems); | |
for (int i = 0; i < nItems; ++i) { | |
values.add(rnd.nextInt(1000)); // Values between 0 and 999, inclusive. | |
} | |
// Limit argument for filtering operation, should cut down the number of elements to ~1% of original. | |
final int limit = 10; | |
// No delay: Baseline. | |
long start = System.currentTimeMillis(); | |
long filteredCount = values.stream().filter(i -> i < limit).map(StreamApiTest::identity).count(); | |
LOGGER.debug("Baseline: Objects filtered and identity-mapped: {}; Time taken: {} ms.", filteredCount, System.currentTimeMillis() - start); | |
// Filtering and then expensive operation. | |
start = System.currentTimeMillis(); | |
filteredCount = values.stream().filter(i -> i < limit).map(StreamApiTest::expensiveOperation).count(); | |
LOGGER.debug("Variation #1: Objects filtered and then expensively-mapped: {}; Time taken: {} ms.", filteredCount, System.currentTimeMillis() - start); | |
// Expensive operation and then filtering. | |
start = System.currentTimeMillis(); | |
filteredCount = values.stream().map(StreamApiTest::expensiveOperation).filter(i -> i < limit).count(); | |
LOGGER.debug("Variation #2: Objects expensively-mapped and then filtered: {}; Time taken: {} ms.", filteredCount, System.currentTimeMillis() - start); | |
} | |
public static Integer expensiveOperation(final Integer input) { | |
try { | |
Thread.sleep(1L); | |
} catch (final InterruptedException e) { | |
// Do nothing, just testing... | |
} | |
return identity(input); | |
} | |
public static Integer identity(final Integer input) { | |
return input; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment