Skip to content

Instantly share code, notes, and snippets.

@farleylai
Last active August 29, 2015 14:02
Show Gist options
  • Save farleylai/36d77ab4e8480bae6374 to your computer and use it in GitHub Desktop.
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.
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);
}
}
@farleylai
Copy link
Author

Results on MacBook Air:

  • testNumberNull(): 1000 to 1400us
  • testNumberOptional(): 2000 to 4000us or more

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment