r/javahelp • u/Forumpy • Feb 21 '20
What are some Java efficiencies you know of?
I want to know more about how to optimise Java code to produce generally better quality and performing code. One of the main optimisations I know of is using StringBuilder instead of concatenating Strings.
What are some other optimisations you know about, and where could I find out more about them?
7
u/RhoOfFeh Feb 21 '20
First, get your code to work.
Second, make your code as clear as you possibly can to the next guy.
At that point you can probably stop unless you have an actual identified performance issue.
5
u/TomahawkChopped Feb 21 '20
First, the most true platitude here is:
The fastest line of code is the one you never write
In terms of Java language and JVM performance, every intermediate/expert developer should eventually understand:
the java memory model, w.r.t. work involved with allocating stack frames, primitives, and heap allocations
Cost of an object reference in terms of time and space
method dispatch in the context of polymorphism
How garbage collection works and what a gc pause costs
At a computer architecture & CS level:
Relative cost in time of going to CPU cache vs main memory vs storage vs network
A rough understanding of big O and how time complexity affects your choice of data structure with respect to your expected use case (e.g. should I use an ArrayList or LinkedList)
General software concepts:
What are the cost/benefit tradeoffs of immutable vs mutable data
Data serialization is expensive... i.e. why marshalling from String <=> Object is so fucking slow
Buffering and related optimizations like copy on write
For a good practice of the above try implementing your own JSON parser and compare it to a serialization solution like ProtoclBuffers, and time the two implementations.
There's probably a dozen more to think of.
But the most important thing here is..... The most expensive resource you will likely ever deal with, is the time it takes you (or other software engineers) to understand the complexity of the code. So any optimizations better have a damn good reason if they are more complicated than the naive solution.
2
Feb 21 '20
Since you seem to be familiar with these topics, can you update your post to have values for some of the items? For instance, if I should know the time cost of an object reference, could you tell me in this public forum instead of just telling me I should know.
3
u/TomahawkChopped Feb 21 '20
No... That's a lot of work for me to write everything here.
You can Google each of those topics above and find more information. As a start I'll recommend the JVM spec if you're really interested
https://docs.oracle.com/javase/specs/jvms/se11/html/jvms-2.html
1
4
u/philipwhiuk Employed Java Developer Feb 21 '20
https://wiki.c2.com/?PrematureOptimization
I honestly don't worry about StringBuilder. I try to write maintainable code - if it's easy to understand it'll be easy to refactor into something optimised when I (or my colleagues) know what the optimisation problem is (memory/CPU/disk/latency/thread count).
1
u/sebnukem Feb 21 '20
Concatenating strings is fine (better). The compiler will use StringBuilder whether you want it or not.
1
u/tedyoung Java Trainer/Mentor Feb 21 '20
Make it readable and well-factored, and then use a profiler and other measurement tools to tell you exactly where the bottleneck is. Encapsulating your data structures will make the process of switching to a more performant data structure easy, e.g., maybe you started out with List, but now it's bigger than you thought it'd be, so switch to Map (or a custom-optimized List) and no other code outside that class has to change.
0
u/proskillz Some Skillz Feb 21 '20
These aren't really Java specific, but they still matter and I see these errors all over the place.
when streaming data off a wire, work directly with the stream if you can. Don't load the whole thing into an array before working with the data.
when you know the length of an object you're loading into a list, use an ArrayList and size it properly.
when you don't know the end length of an object, use a LinkedList instead.
if you're pulling back large datasets from Hibernate that don't need JPA, switch that to raw JDBC or some other solution (keeping in mind #2 and #3).
if you need to iterate over an ordered map, use TreeMap instead of HashMap. You shouldn't be doing Collections.sort(map.entrySet()).
1
u/dastardly740 Feb 21 '20
3 reminded me of something I screwed up a long time ago.
Tldr; Use iterators to loop on Collections or pretty much any Iterable.
get(index) for LinkedList has to traverse from the start or end of the list to get the item at index. So, for loop using a counter to get each item is O(n2) which was nasty when I encountered a very long list. One answer is use ArrayList. But why worry about implementation details? Plus you should program to interfaces. So, you might not even know what List implementation is being passed. Even better program to Iterable so the type of Collection is irrelevant for the loop.
21
u/Northeastpaw Feb 21 '20
For the most part don't worry about it. Even the StringBuilder advice is mostly obsolete; string concatenation outside of loops will automatically be converted to StringBuilders by the compiler.
The JIT is really, really good at optimizing hot paths. Trying to hand optimize those same paths might make it so the JIT can't do its best when it takes a go at it. Focus on making your code readable and maintainable first. If you notice performance problems at runtime first profile to find the badly performing code and then try optimizing it. Otherwise just let the JIT handle it most time.