Last active
August 29, 2015 14:02
-
-
Save farleylai/36d77ab4e8480bae6374 to your computer and use it in GitHub Desktop.
Though Java 8 introduces the Optional class to improve readability and prevent NullPointerException, implicit performance overhead in inevitable in the following test cases.
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
public class JavaTest { | |
long nanos; | |
@Before | |
public void setUp() { | |
System.gc(); | |
nanos = System.nanoTime(); | |
} | |
@After | |
public void tearDown() { | |
nanos = System.nanoTime() - nanos; | |
System.out.printf("time elapse: %.3fms\n", nanos / 1000.0); | |
} | |
private Number getNumberNull(int n) { | |
return n == 777 ? new Integer(777) : null; | |
} | |
private Optional<Number> getNumberOptional(int n) { | |
return n == 777 ? Optional.of(777) : Optional.empty(); | |
} | |
@Test | |
public void testNumberNull() { | |
int count = 0; | |
for(int i = 0; i < 10000; i++) { | |
Number number = getNumberNull(i); | |
if(number != null) count += number.intValue(); | |
} | |
assertEquals(777, count); | |
} | |
@Test | |
public void testNumberOptional() { | |
int count = 0; | |
for(int i = 0; i < 10000; i++) { | |
Optional<Number> number = getNumberOptional(i); | |
if(number.isPresent()) count += number.get().intValue(); | |
} | |
assertEquals(777, count); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Results on MacBook Air: