Tuesday, July 22, 2025

Optimise your Java code with a few simple tips

(Originally published in LinkedIn)

As a Java developer, it's essential to write efficient and performant code. But with so many different techniques and approaches to choose from, it can be challenging to know where to start. As applications grow in size and complexity, it's essential to ensure that they perform well and don't become a bottleneck for your users. In this post, we'll explore some tips and tricks for optimizing Java code performance, with code examples to help you understand the concepts better.

Use Primitive Types

Java provides a number of wrapper classes for primitive types such as Integer, Long, etc. These classes are useful for object-oriented programming, but they come with a performance overhead. When you need to perform arithmetic operations or store large amounts of data, it's better to use the corresponding primitive types like int, long, etc.

// Using Integer
Integer i = new Integer(100);

// Using int
int i = 100;

Another example, if you're working with a large array of integers, it's more efficient to use an int[] rather than an Integer[].

java
int[] numbers = new int[100];

Use ArrayList Instead of LinkedList

LinkedList is a great choice when you need to perform a lot of insertions and deletions in the middle of a list. However, if you're working with a large number of elements and need to access them frequently, ArrayList is a better choice. ArrayList is faster than LinkedList because it uses an array to store elements, which allows for faster access times.

List<Integer> numbers = new ArrayList<>();

Use the Right Collection

Java provides several different collections, each with its own strengths and weaknesses. For example, HashMap is a great choice if you need to perform a lot of lookups, while LinkedHashMap is better for maintaining the order of elements.

Map<String, Integer> map = new HashMap<>();

Another often forgotten collections are the enum oriented collections, such as EnumMap, or EnumSet, optimised for working with enums:.

Map<Month, String> m = new EnumMap(Month.class);
m.put(Month.MAY, "John");

Set<Month> quarters = EnumSet.of(Month.MARCH, Month.JUNE, Month.SEPTEMBER, Month.DECEMBER);

Use StringBuilder instead of String Concatenation

When concatenating strings in Java, it's tempting to use the + operator, but this can be slow and inefficient. A better option is to use the StringBuilder class, which is optimized for concatenation operations. It is true that in trivial cases, the compiler can replace concatenations with StringBuilders. In non-trivial cases, such as loops, there is not much the compiler can do.

 // Using String concatenation
String s = "Hello" + "World";

StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append("World");
String s = sb.toString();

Avoid Excessive Method Calls

Java's virtual machine needs to look up the correct method to call each time a method is invoked. This process can add significant overhead to your code, especially when the method calls are nested or happen frequently. To avoid this, try to minimize the number of method calls, or use a caching mechanism to speed up the process.

// Excessive method calls
int sum = 0;
for(int i = 0; i < 100; i++) {
    sum += getValue(i);
}

// Minimizing method calls
int sum = 0;
int[] values = getValues();
for(int i = 0; i < 100; i++) {
    sum += values[i];
}

Use the Right Loop

When iterating through a collection, it's essential to use the right loop. For example, if you're working with an array, it's more efficient to use a for loop than an iterator.

int[] numbers = {1, 2, 3, 4, 5};
for (int i = 0; i < numbers.length; i++) {
    System.out.println(numbers[i]);
}

Use Multi-threading

Java's multi-threading capabilities can be used to improve the performance of your code. By running multiple threads in parallel, you can take advantage of multiple cores and processors on your machine, which can speed up your code significantly.

// Using multithreading
Thread t1 = new Thread(() -> {
    // Thread 1 code
});
Thread t2 = new Thread(() -> {
    // Thread 2 code
});
t1.start();
t2.start();

More sophisticated solutions can be made with fork-and-join framework and executors.

These are just a few tips and tricks for optimizing Java code performance. By following these best practices, you can improve the performance of your code

No comments:

Post a Comment

The Gladiator’s Leap: Did Predatory Combat Ignite the Spark of Avian Flight?

  Forget the "trees-down" vs. "ground-up" debate. The true origins of the avian power stroke may lie in the brutal arena...