20 Essential Java Coding Practices to Boost Performance and Prevent Memory Leaks

This article presents a comprehensive list of Java coding guidelines—including using final classes, reusing objects, favoring local variables, avoiding unnecessary initializations, and optimizing collections—to reduce resource consumption, improve execution speed, and mitigate memory‑leak risks.

ITFLY8 Architecture Home
ITFLY8 Architecture Home
ITFLY8 Architecture Home
20 Essential Java Coding Practices to Boost Performance and Prevent Memory Leaks

Resources such as memory, CPU time, and network bandwidth are limited; optimization aims to accomplish tasks with minimal resources. This article focuses on improving Java code efficiency.

1. Prefer the final modifier for classes

Marking a class as final prevents inheritance, allowing the JVM to inline final methods, which can raise performance by up to 50%.

2. Reuse objects whenever possible

When concatenating strings, use StringBuffer (or StringBuilder) instead of creating many temporary String objects, which would increase garbage‑collection overhead.

3. Use local variables

Method parameters and temporary variables stored on the stack are accessed faster than static or instance fields that reside on the heap.

4. Avoid redundant variable initialization

Java automatically initializes fields to default values (null, 0, false, etc.). Re‑initializing them in constructors adds unnecessary work.

5. Write SQL keywords in uppercase

In Java‑Oracle applications, using uppercase SQL statements eases the Oracle parser’s workload.

6. Close database connections and I/O streams promptly

Large objects such as connections and streams consume significant resources; always close them after use.

7. Help the garbage collector

After an object is no longer needed, set its reference to null to make it eligible for collection sooner, because the JVM may not reclaim it immediately.

8. Prefer method‑level synchronization over block synchronization

Method synchronization is generally more efficient than synchronizing small code blocks.

9. Reduce repeated calculations in loops

Cache collection size before the loop:

int len = list.size();
for (int i = 0; i < len; i++) {
    // ...
}

10. Apply lazy loading

Instantiate objects only when they are actually needed.

11. Use exceptions sparingly

Throwing an exception creates a new object and captures a stack trace, which is costly; exceptions should signal errors, not control flow.

12. Move try‑catch blocks outside tight loops

Place exception handling at the outermost level to avoid repeated overhead.

13. Efficient use of StringBuffer

Choose an appropriate initial capacity to avoid frequent resizing: StringBuffer sb = new StringBuffer(256); // example capacity Use ensureCapacity(int) if the needed size is known after construction.

14. Proper use of java.util.Vector

Pre‑size a Vector when the number of elements is known to avoid repeated array copying:

Vector v = new Vector(100000);
for (int i = 0; i < 100000; i++) {
    v.add(obj);
}

Removing elements from the end is far cheaper than from the beginning; use remove(v.size() - 1) or removeAllElements() when clearing.

15. Use System.arraycopy for bulk copying

int[] src = {1,3,5,6,7,8};
int[] dest = new int[6];
System.arraycopy(src, 0, dest, 0, 6);

16. Refactor code for readability

Example of a cleaner shopping‑cart class:

public class ShopCart {
    private List carts;
    public void add(Object item) {
        if (carts == null) {
            carts = new ArrayList();
        }
        carts.add(item);
    }
    public void remove(Object item) {
        if (carts != null && carts.contains(item)) {
            carts.remove(item);
        }
    }
    public List getCarts() {
        return Collections.unmodifiableList(carts);
    }
}

17. Create objects without the new keyword when possible

Use cloning for objects that implement Cloneable or employ factory methods that return pre‑created instances.

18. Replace multiplication/division with bit shifts

Multiplying by powers of two can be expressed as left shifts, which are faster:

for (int val = 0; val < 100000; val += 5) {
    int alterX = val << 3; // val * 8
    int myResult = val << 1; // val * 2
}

19. Disable unnecessary HTTP sessions in JSP

Add the page directive <%@ page session="false" %> to prevent automatic session creation for pages that do not need it.

20. Optimize JDBC data retrieval

Increase the fetch size to reduce round‑trips to the database. For example, setting the fetch size to 512 rows cuts the number of calls dramatically when processing large result sets.

Source: cnblogs.com

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Memory ManagementCode Refactoringbest practices
ITFLY8 Architecture Home
Written by

ITFLY8 Architecture Home

ITFLY8 Architecture Home - focused on architecture knowledge sharing and exchange, covering project management and product design. Includes large-scale distributed website architecture (high performance, high availability, caching, message queues...), design patterns, architecture patterns, big data, project management (SCRUM, PMP, Prince2), product design, and more.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.