Member-only story

Lesser Known Java Optimizations That Make a Big Difference

These minor refactors can drastically improved efficiency

Skilled Coder
6 min read6 days ago
Photo by Tirza van Dijk on Unsplash

Performance optimizations in Java are often associated with big refactors, but sometimes, small tweaks can bring significant speed improvements.

There are many lesser-known optimizations that can make your Java code faster, more efficient, and scalable with minimal effort.

I have also shared real world use case which will give you idea where it can be impactful.

1. Bitwise Operations Over Modulo for Power-of-2 Checks

Using %(modulo) to check indices or wrap counters is slower than bitwise operations when dealing with powers of 2 (e.g., 2, 4, 8, 16).

Instead of

int capacity = 16;
int index = 0;
for (int i = 0; i < 100000; i++) {
index = (index + 1) % capacity; // Modulo is a division operation
}

Use

int capacity = 16; // Must be power of 2
int mask = capacity - 1; // 15 (0b1111)
int index = 0;
for (int i = 0; i < 100000; i++) {
index = (index + 1) & mask; // Bitwise AND replaces modulo
}

For powers of 2, x % n is equivalent to x & (n-1) because n-1 creates a bit mask. Bitwise AND

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Skilled Coder
Skilled Coder

Written by Skilled Coder

Sharing content and inspiration on programming. Coding Newsletter : https://skilledcoder.substack.com

Responses (13)

Write a response

Some books for reference points
- "Java Performance: The Definitive Guide" by Scott Oaks
- "Java Performance" by Charlie Hunt 2011
- "Java Concurrency in Practice" by Brian Goetz
- "Effective Java" by Joshua Bloch

In general do not try those micro optimizations... first write readable and testable code... and if you think you have a performance issue... measure first ... and based on those results try to dig to the root cause and optmize exactly that... anything else will lead to hard to read and unmaintainable code....

9. Avoid Boxing in Stream Reductions

What does "mapToInt" do ? It does an unboxing....