🌐
JetBrains
blog.jetbrains.com › idea › 2024 › 02 › java-best-practices
Java Best Practices | The IntelliJ IDEA Blog
September 17, 2025 - Not closing resources in a try block can cause memory issues and application errors, impacting performance and reliability. ... In the example below, we handle the system resource FileInputStream manually, which may lead to a resource leak and other problems if an exception is thrown while closing. ... In the improved version, declaring FileInputStream inside the try block means Java will automatically close it, regardless of whether we leave the try block normally or with an exception. Deeply nested code highlights logical issues that can be difficult to notice initially.
🌐
Raygun
raygun.com › blog › java-performance-optimization-tips
Java performance optimization tips: How to avoid common pitfalls · Raygun Blog
April 13, 2023 - Streams are a great addition to the Java language, letting you easily lift error-prone patterns from for loops into generic, more reusable blocks of code with consistency guarantees. But this convenience doesn’t come for free; there is a performance cost associated with using streams. Thankfully this cost isn’t usually too high - at best, a few % faster, and at worst 10-30% slower for common operations - but it is something to be aware of.
Discussions

Java Code Optimisation Techniques
code optimisation technique Do you mean 'optimize' in the sense of 'make it run faster / use less resources'? I hope not. They've all been debunked, so that's a bad start. At least, not 'all', but most. Here is a trivial example: Let's say you want to convert a list of strings into an array of strings. There are many ways to do that: String[] arr = list.toArray(new String[0]); String[] arr = list.toArray(new String[list.size()]); String[] arr = list.toArray(String[]::new); Time them. Seriously. If you want to write this paper do this, and do it right (use JMH ). You'll find that they all take equally long. This goes in the face of every obvious performance advice you care to give! "Lambdas are slow!" would disqualify the third. "Object creation is best avoided" would disqualify the first, which seems strictly worse than the second (The API of toArray states that if you pass in an array object that is too small, then the toArray method will use your array solely to derive its component type (String.class here), and otherwise discard it; it makes a new properly sized array and returns that. In other words, it does reflective introspection on the argument and ends up making a new array of size list.size() anyway, using reflection again no less. So option 1 should be vastly slower than 2, right? Nope. At least, JMH says nope, and I trust JMH here. We're basically down to the following 3 rules of thumb: Code that is well known to be an obvious and immediate resource drain should be avoided. The 'duh' rule. Don't use known-slow libraries. Don't use a network based software-as-a-service to do a padLeft operation. This doesn't take a paper to explain, this takes a tiny smidge of common sense. Algorithmic complexity. Bubble sort is slower than Quick sort because if you chart out the performance of these vs. the size of the input, you know, mathematically, that quicksort's graph ends up looking like y = n * log(n) and bubblesort's looks like y = x^2. This is mathematically provable and it means that as long as random factors like hotspot, CPU pipeline optimizations and all that sort of thing can never score O(n^2) optimizations (which it can't), bubblesort will ALWAYS lose from quicksort if only the input is big enough. This is more a math topic than programming. Nothing means anything until you have a combination of 2 facts, and you really do need both: [A] you have a real world situation and the code in this scenario is not running as fast as you'd expected it to / as the requirements demand it to, and [B] you have a profiler report that tells you precisely which 1% of the code is eating 99% of the CPU resources. How do you optimize this final 1%? It's usually obvious, but crucially, optimizing anything in the other 99% is UTTERLY POINTLESS and is only making your life worse! Generally to optimize code you need to tweak how it works, which usually involves tweaking the 'pipeline' (the way data flows into, and out of, this 1% crucial path code). The more you mess up your code by trying to chase pointless performance enhancements, the harder that is. Hence: The fastest code is the cleanest, most flexible, testable, and readable code. Combining the rule of 'if the profiler / JMH says it doesn't matter, then it doesn't matter' and 'the easiest to read and test code is the best because it lends itself the best to performance tweaking once you do have that profiler report in hand', then there is only one right answer, which is that list.toArray(new String[list.size()]) is the only one of the three that is objectively wrong. And yet it sure seems like the one that ought to perform the best. More on reddit.com
🌐 r/java
46
76
April 18, 2021
performance - What are some best practices to build memory-efficient Java applications? - Stack Overflow
Java programs can be very memory hungry. For example, a Double object has 24 bytes: 8 bytes of data and 16 bytes of JVM-imposed overhead. In general, the objects that represent the primitive type... More on stackoverflow.com
🌐 stackoverflow.com
profiling - Java performance tips - Stack Overflow
I have a program I ported from C to Java. Both apps use quicksort to order some partitioned data (genomic coordinates). The Java version runs fast, but I'd like to get it closer to the C version.... More on stackoverflow.com
🌐 stackoverflow.com
Video: Secure Coding Guidelines for Java SE
Section SERIAL-6 is important, but IMHO should go further -- if you are not using Java serialization in your application, you should disable it completely via a JVM-wide ObjectInputFilter. I don't think I'll ever write another application that doesn't flip the Java serialization switch from "on by default" to "off by default". The advice in the video to skip this section if you are not using Java serialization is a bit misleading -- by default you're always at risk of using it, even if you didn't mean to. More on reddit.com
🌐 r/java
1
22
January 4, 2023
🌐
Medium
medium.com › javarevisited › java-performance-optimization-tips-and-techniques-d79e63d040b4
Java Performance Optimization: Tips and Techniques | by Ionut Anghel | Javarevisited | Medium
March 24, 2023 - In this article, we’ll explore some practical tips and techniques for Java performance optimization, including the use of data structures, memory management, and concurrency. Selecting the appropriate data structure for your use case is vital for achieving optimal performance. Java provides a wide range of data structures in its Collections Framework, such as ArrayList, LinkedList, HashMap, and TreeSet. Understand their performance characteristics and choose the one that best ...
🌐
Medium
medium.com › javarevisited › 10-java-performance-secrets-every-senior-developer-knows-36c8db40ba08
10 Java Performance Secrets Every Senior Developer Knows | by Pudari Madhavi | Javarevisited | Medium
July 22, 2025 - In this article, I’ll walk you through 10 powerful Java optimization techniques that can significantly improve the performance of your application. No vague tips — I’ll back each point with real code examples, and explain why it matters in real-world scenarios. Whether you’re building a high-load backend, a microservice, or a data processing engine, these techniques will give you the edge. String result = ""; for (int i = 0; i < 1000; i++) { result += i; }
🌐
Reddit
reddit.com › r/java › java code optimisation techniques
r/java on Reddit: Java Code Optimisation Techniques
April 18, 2021 -

I’m currently writing my dissertation on code optimisation techniques in Java. I’m currently doing my literature review and was wondering if anyone has good resources for code optimisations specifically (excluding JVM tuning).

Sorry if this is classed as learning and not appropriate.

I am looking at time and space complexity of different data structures, data types, JCF, class initialisation and so on.

Top answer
1 of 5
70
code optimisation technique Do you mean 'optimize' in the sense of 'make it run faster / use less resources'? I hope not. They've all been debunked, so that's a bad start. At least, not 'all', but most. Here is a trivial example: Let's say you want to convert a list of strings into an array of strings. There are many ways to do that: String[] arr = list.toArray(new String[0]); String[] arr = list.toArray(new String[list.size()]); String[] arr = list.toArray(String[]::new); Time them. Seriously. If you want to write this paper do this, and do it right (use JMH ). You'll find that they all take equally long. This goes in the face of every obvious performance advice you care to give! "Lambdas are slow!" would disqualify the third. "Object creation is best avoided" would disqualify the first, which seems strictly worse than the second (The API of toArray states that if you pass in an array object that is too small, then the toArray method will use your array solely to derive its component type (String.class here), and otherwise discard it; it makes a new properly sized array and returns that. In other words, it does reflective introspection on the argument and ends up making a new array of size list.size() anyway, using reflection again no less. So option 1 should be vastly slower than 2, right? Nope. At least, JMH says nope, and I trust JMH here. We're basically down to the following 3 rules of thumb: Code that is well known to be an obvious and immediate resource drain should be avoided. The 'duh' rule. Don't use known-slow libraries. Don't use a network based software-as-a-service to do a padLeft operation. This doesn't take a paper to explain, this takes a tiny smidge of common sense. Algorithmic complexity. Bubble sort is slower than Quick sort because if you chart out the performance of these vs. the size of the input, you know, mathematically, that quicksort's graph ends up looking like y = n * log(n) and bubblesort's looks like y = x^2. This is mathematically provable and it means that as long as random factors like hotspot, CPU pipeline optimizations and all that sort of thing can never score O(n^2) optimizations (which it can't), bubblesort will ALWAYS lose from quicksort if only the input is big enough. This is more a math topic than programming. Nothing means anything until you have a combination of 2 facts, and you really do need both: [A] you have a real world situation and the code in this scenario is not running as fast as you'd expected it to / as the requirements demand it to, and [B] you have a profiler report that tells you precisely which 1% of the code is eating 99% of the CPU resources. How do you optimize this final 1%? It's usually obvious, but crucially, optimizing anything in the other 99% is UTTERLY POINTLESS and is only making your life worse! Generally to optimize code you need to tweak how it works, which usually involves tweaking the 'pipeline' (the way data flows into, and out of, this 1% crucial path code). The more you mess up your code by trying to chase pointless performance enhancements, the harder that is. Hence: The fastest code is the cleanest, most flexible, testable, and readable code. Combining the rule of 'if the profiler / JMH says it doesn't matter, then it doesn't matter' and 'the easiest to read and test code is the best because it lends itself the best to performance tweaking once you do have that profiler report in hand', then there is only one right answer, which is that list.toArray(new String[list.size()]) is the only one of the three that is objectively wrong. And yet it sure seems like the one that ought to perform the best.
2 of 5
19
Don't get stuck in the trap of "Oh i used a linkedlist rather than an array list, that's obviously why it was slow". JVM and modern hardware can also easily make these problems far less consequential than higher level algorithmic or design problems. Beware that this also makes microbenchmarking a non-trivial exercise of comparing two small pieces of code in isolation vs a real running program. Quick example is that linkedlist can actually be slower than a an array when small due to an array list having everything in one CPU cache line, whereas linked list may have pointer references going all over the heap. measure measure measure analyse - This is the true hard part of the problem in my opinion Does this code even need to run, is it running too often - The fastest code is code that doesn't run Is it blocking on something, network calls etc, Is it re-computing something that could be cached that is an easy memory trade off experiment a change (this is where at least knowning the theory of the data structures may help) Did you actually fix the issue? Re-measure! What was second place in original measures may also totally disappear, so restart the process again if you still need better performance
🌐
DEV Community
dev.to › omal_jayamanne_ › java-coding-best-practices-for-high-performance-applications-3aea
Java Coding Best Practices for High-Performance Applications - DEV Community
April 25, 2025 - In the fast-paced world of software development, writing efficient and high-performance Java code is critical for building scalable applications. Whether you're optimizing for speed, minimizing resource usage, or handling large datasets, mastering Java best practices can make a significant difference.
🌐
Stackify
stackify.com › java-performance-tuning
11 Simple Java Performance Tuning Tips - Stackify
March 20, 2024 - We’re going to cover all the ... to the Java platform. Let’s get started. That might be one of the most important performance tuning tips. You should follow common best practices and try to implement your use cases efficiently. But that doesn’t mean that you should replace any standard libraries or build complex optimizations before you proved that it’s necessary. In most cases, premature optimization takes up a lot of time and makes the code hard to read ...
Find elsewhere
🌐
Keyhole Software
keyholesoftware.com › home › 8 proven ways to optimize java code performance
8 Proven Ways to Optimize Java Code Performance
January 28, 2025 - Learn 8 proven ways to optimize Java code performance with efficient data structures, caching, and garbage collection.
🌐
GeeksforGeeks
geeksforgeeks.org › java › tips-to-optimize-java-code-performance
12 Tips to Optimize Java Code Performance - GeeksforGeeks
July 23, 2025 - By following simple tips like keeping methods short, avoiding excessive if-else statements, using StringBuilder for concatenation, and choosing primitive types, you can write efficient code from the start.
🌐
Javapro
javapro.io › home page › hitchhiker’s guide to java performance
Hitchhiker's Guide to Java Performance - JAVAPRO International
April 7, 2025 - The JNI overhead made native libraries inefficient, which is why performance-critical code was often written in C/C++. Differences in thread scheduling made optimal tuning difficult, as early JVMs did not map Java threads 1:1 to OS threads. Nevertheless, these years laid the foundation for later optimizations: With JIT, generational GC and native threads, Java became significantly faster and more scalable around 2000, a trend that still characterizes the platform today.
Top answer
1 of 7
5

Some techniques I use to reduce memory:

  • Make your own IntArrayList (etc) class that prevents boxing
  • Make your own IntHashMap (etc) class where keys are primitives
  • Use nio's ByteBuffer to store large arrays of data efficiently (and in native memory, outside heap). It's like a byte array but contains methods to store/retrieve all primitive types from the buffer at any arbitrary offset (trade memory for speed)
  • Don't use pooling because pools keep unused instances explicitly alive.
  • Use threads scarcely, they're super memory hungry (in native memory, outside heap)
  • When making substrings of big strings, and discarding the original, the substrings still refer to the original. So use new String to dispose of the old big string.
  • A linear array is smaller than a multidimensional array, and if the size of all but the last dimension is a power of two, calculating indices is fastest: array[x|y<<4] for a 16xN array.
  • Initialize collections and StringBuilder with an initial capacity chosen such that it prevents internal reallocation in a typical circumstance.
    • Use StringBuilder instead of string concatenation, because the compiled class files use new StringBuilder() without initial capacity to concatenate strings.
2 of 7
4

Depends on the application, but generally speaking

  • Layout data structures in (parallel) arrays of primitives

  • Try to make big "flat" objects, inlining otherwise sensible sub-structures

  • Specialize collections of primitives

  • Reuse objects, use object pools, ThreadLocals

  • Go off-heap

I cannot say these practices are "best", because they, unfortunately, make you suffer, losing the point why you are using Java, reduce flexibility, supportability, reliability, testability and other "good" properties of the codebase.

But, they certainly allow to lower memory footprint and GC pressure.

🌐
TatvaSoft
tatvasoft.com › home › java best practices for developers
Java Best Practices for Developers - TatvaSoft Blog
February 18, 2026 - Creating proper project & source files structures, using proper naming conventions, avoiding unnecessary objects and hardcoding, commenting the code in a correct way helps in maintaining the Project Code effectively.
Top answer
1 of 14
35

do not try to outsmart the jvm.

in particular:

  • don't try to avoid object creation for the sake of performance

  • use immutable objects where applicable.

  • use the scope of your objects correctly, so that the GC can do its job.

  • use primitives where you mean primitives (e.g. non-nullable int compared to nullable Integer)

  • use the built-in algorithms and data structures

  • when handing concurrency use java.util.concurrent package.

  • correctness over performance. first get it right, then measure, then measure with a profiler then optimize.

2 of 14
11

Obviously, profile profile profile. For Eclipse there's TPTP. Here's an article on the TPTP plugin for Eclipse. Netbeans has its own profiler. jvisualvm is nice as a standalone tool. (The entire dev.java.net server seems to be down at the moment, but it is very much an active project.)

The first thing to do is use the library sorting routine, Collections.sort; this will require your data objects to be Comparable. This might be fast enough and will definitely provide a good baseline.

General tips:

  • Avoid locks you don't need (your JVM may have already optimized these away)
  • Use StringBuilder (not StringBuffer because of that lock thing I just mentioned) instead of concatenating String objects
  • Make anything you can final; if possible, make your classes completely immutable
  • If you aren't changing the value of a variable in a loop, try hoisting it out and see if it makes a difference (the JVM may have already done this for you)
  • Try to work on an ArrayList (or even an array) so the memory you're accessing is contiguous instead of potentially fragmented the way it might be with a LinkedList
  • Quicksort can be parallelized; consider doing that (see quicksort parallelization)
  • Reduce the visibility and live time of your data as much as possible (but don't contort your algorithm to do it unless profiling shows it is a big win)
🌐
Medium
medium.com › @amitvsolutions › code-optimization-java-35bee3a478c2
Code Optimization- JAVA
May 28, 2024 - Shallow object hierarchies simplify the code and improve performance. NOTE: Better think of composition instead of inheritance. ... Explanation: Eager initialization creates objects even if they may not be used, leading to unnecessary resource ...
🌐
DEV Community
dev.to › adityabhuyan › best-practices-and-techniques-for-optimizing-java-code-performance-3jh9
Best Practices and Techniques for Optimizing Java Code Performance - DEV Community
July 18, 2024 - Certain practices can degrade performance. Avoid the following: Excessive Synchronization: Over-synchronization can lead to thread contention and performance issues. Reflection: Reflection is slow and should be avoided in performance-critical code.
🌐
SkillReactor Blog
skillreactor.io › home › java best practices: code efficiently & securely
Java Best Practices: Code Efficiently & Securely - SkillReactor Blog
March 19, 2024 - Optimizing Java code can lead to better application performance. Implementing security best practices protects your Java applications from threats. Managing dependencies and collaborating effectively streamline Java development processes. Following coding standards and best practices is crucial for producing high-quality, efficient, secure code in Java development.
🌐
Quora
quora.com › How-can-I-optimize-Java-code-for-improved-performance-and-efficiency-in-my-program
How to optimize Java code for improved performance and efficiency in my program - Quora
Answer: One can easily optimize java code by following certain rules: - 1. Avoid Writing Long methods: - It is for better performance while class loading since the methods are loaded in the stack memory.
🌐
TutorialsPoint
tutorialspoint.com › 12-tips-to-optimize-java-code-performance
12 Tips to Optimize Java Code Performance
July 12, 2023 - For instance, choosing a LinkedList over an ArrayList can be advantageous if you frequently add or delete entries from a list because it has constant time complexity for these operations as opposed to the linear time complexity of an ArrayList. HashMap, TreeSet, and PriorityQueue are a few other effective data structures to take into account. You can improve your Java code's overall performance by utilizing these data structures.