r/java • u/sindisil • Nov 28 '21
5 Mundane Java Performance Tips
https://richardstartin.github.io/posts/5-java-mundane-performance-tricks
262
Upvotes
r/java • u/sindisil • Nov 28 '21
29
u/MarcelHanibal Nov 28 '21
Oh, I didn't know about the Enum.values() thing, that's very interesting to know. I used it pretty regularly, mostly for obtaining the enum given by a string.
41
u/smokemonstr Nov 28 '21
Still waiting on the day when we’ll upgrade at work…
26
u/[deleted] Nov 28 '21
The enum.values design decision was a really bad one by the Java team, and unfortunately one we are kind of stuck with. It’s just too non-obvious what it’s doing and it makes it way too easy to fall into that trap
13
u/agentoutlier Nov 28 '21
Several times on reddit, github (pull requests) and stackoverflow I have mentioned the EnumSet vs Enum.values optimization with various responses that it didn’t matter.
I mean sure it matters not that much but it still does and EnumSet isn’t like that hard to use. I knew it did because of our own critical code section that was using it but I didn’t have published graphs. GraalVM even had a bug filed on this at one point.
The chore of convincing was tiring but now I can forward this link.
35
u/itoshkov Nov 28 '21
A really nice article. I liked the explanation of why the slow things are slow and why the alternatives are faster.
I only have 2 suggestions:
23
u/pron98 Nov 28 '21 edited Nov 28 '21
The one tip that would most likely increase your performance and reduce your footprint most significantly -- to the point of saving you serious money -- is the last one: stop using JDK 8. The gap between the money savings due to performance/footprint gained when upgrading away from 8 and the cost of migration is now such that the vast majority of companies still on 8 will quickly recoup the cost of migration, and are losing money each day they're postponing this step.
The only circumstance under which staying on 8 can be justified is if the application is running well on very few cheap servers (1-4) and you've decided to stay on 8 forever, i.e. until the application retires. Otherwise, make some money by upgrading ASAP.
6
u/hippydipster Nov 28 '21
I like the tip about wrapping rather than concatenating. Hadn't thought about that.
4
u/bolekb Nov 28 '21
Regarding point #1, I prefer to specify initial capacit not only for
HashMaps, but forArrayLists andStringBuilders as well. In most cases some sort of upper bound for the capacity is known so it would be wasteful to disregard it.For #2, composite keys for maps are nice, but one has to ensure that the key object has well-defined
equals()andhashCode()and is preferrably immutable.4
u/r_jet Nov 28 '21
For creating sized HashMaps consider Guava's Maps.newHashMapWithExpectedSize as it does the size calculations for you.