Optimization is one of the major concerns when working with Java applications. Our code should be bug-free and optimized, and the execution time of the code must be within the desired limit.
We should consider the standards defined by Java in this area, as we are sometimes unable to find time to analyze the code.
Some techniques are quite helpful for writing optimized code, such as those listed below:
if-else
conditional statements.BigDecimal
class.if-else
conditional statementsThe usage of conditional statements in code is quite important for decision-making. We must limit the usage of these statements, as they can affect the performance of the code.
We can consider using the switch
statement instead of using multiple if-else
statements.
The approach below should be avoided:
if(con1) {
if(con2) {
if(con3 || con4) { execution.....}
else { execution.....}
. . . . .
}
}
Here is the better approach:
boolean ans = (con1 && con2) && (con3 || con4)
We should also avoid writing long methods. During the call of methods, they are loaded in a part of the memory called the stack.
If these methods are too large, they will use up a significant amount of memory, so we must try to break them into smaller methods by considering how to split the logic.
An object of the String
class can never be reused because it is an immutable class. For better optimization, avoid using the +
operator to concatenate a large string, which results in using more heap memory.
We should avoid the following approach:
String str = str1 + str2 + str3;
The better approach that uses the StringBuilder
class is as follows:
StringBuilder objSB = new StringBuilder("");
objSB.append(str1).append(str2).append(str3);
String str = objSB.toString();
We can use primitive types over objects to achieve optimization. Objects are stored on heap memory, while primitive types are stored on the stack.
We can access data from the stack faster than the heap, so primitive types provide better optimization.
Another technique that should be considered to improve optimization is the usage of stored procedures instead of long queries.
Stored procedures are pre-compiled and are stored in a database as objects. They are executed in less time, so they help provide memory optimization.
BigDecimal
classThe BigDecimal
class is helpful for providing decimal values for accurate precision. We can perform multiple operations like arithmetic operations, comparison, manipulation, rounding, hashing, format conversion, etc.
However, excessive use of this class can affect the performance of Java code. We can use the long
and double
types with proper casting instead of BigDecimal
for improved optimization.