KEMBAR78
Refactoring to Java 8 (Devoxx UK) | PDF
@trisha_gee#DevoxxUK
Refactoring to Java 8
Trisha Gee, JetBrains
@trisha_gee
trishagee.com
Why Java 8?
It’s Faster
•Performance Improvements in Common Data
Structures
•Fork/Join Speed Improvements
•Changes to Support Concurrency
•…and more
http://bit.ly/refJ8
Easy to Parallelize
Fewer lines of code
Minimizes Errors
Safety Check
Test Coverage
Performance Tests
Decide on the Goals
Limit the Scope
Morphia
https://github.com/mongodb/morphia
Refactoring!
Lambda Expressions
Automatic Refactoring
•Predicate
•Comparator
•Runnable
•etc…
Abstract classes
Advanced Search
Collections & Streams
Automatic Refactoring
•For loop to collect
•For loop to forEach
•…with and without Streams
Manual Refactoring
Optional
But what about performance?
Lambdas
0
20
40
60
80
100
120
140
160
180
Ops/ms Lambdas vs Anonymous Inner Classes
Anonymous Inner Class Lambda


http://www.oracle.com/technetwork/java/jvmls2013kuksen-2014088.pdf
0
2
4
6
8
10
12
14
16
18
20
single thread max threads
nsec/op
Performance of Capture
anonymous(static) anonymous(non-static) lambda 

0
50,000
100,000
150,000
200,000
250,000
300,000
350,000
400,000
450,000
500,000
Constant message Variable message
Ops/ms Logging Performance
Lambda Direct call


Streams vs Iteration
0
1
2
3
4
5
6
7
8
9
Ops/ms Iterator vs Stream
for loop forEach()


Going parallel
0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
Serial Parallel
TimeTaken(seconds) map()
MacBook Surface


0
20
40
60
80
100
120
140
160
Serial Parallel
TimeTaken(millis) findAny()
MacBook Surface


Optional
0
50,000
100,000
150,000
200,000
250,000
300,000
350,000
Value not null Value null
Ops/ms Compare Constant Field Value with Null
Null check Optional


0
50,000
100,000
150,000
200,000
250,000
300,000
Value not null Value null
Ops/ms Compare Variable Field Value with Null
Null check Optional


Summary
Sometimes new idioms decrease clutter
…but sometimes they don’t
Sometimes the new features improve
performance
0
20
40
60
80
100
120
140
160
180
Ops/ms Lambdas vs Anonymous Inner Classes
Anonymous Inner Class Lambda
…and sometimes they don’t
0
50,000
100,000
150,000
200,000
250,000
300,000
Value not null Value null
Ops/ms Compare Variable Field Value with Null
Null check Optional
Sometimes a new feature makes life easier
…sometimes not so much
Some refactoring can safely be done
automatically
…often you need a human brain
Conclusion
Should you migrate your code to Java 8?
It Depends
Always remember what your goal is
And compare results to it
Understand what may impact performance
And if in doubt, measure
Code may magically improve
Or you may expose areas for improvement
Your tools can help you
But you need to apply your brain too
http://bit.ly/refJ8
@trisha_gee

Refactoring to Java 8 (Devoxx UK)