Member-only story

Lesser Known Java Optimizations That Make a Big Difference

These minor refactors can drastically improved efficiency

Skilled Coder
6 min read3 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

--

--

Skilled Coder
Skilled Coder

Written by Skilled Coder

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

Responses (13)