How to Reduce Time Complexity in Java
What is time complexity?
The time complexity in java is given as the amount of time a program requires to run or execute it
Calculating the time complexity of the program
The time complexity is calculated for many forms as shown below
- Time complexity of a loop
- When the variable is added or subtracted
- When the variable is divided or multiplied
- The time complexity for nested loops
- The time complexity for infinite loops
- The Time complexity of the other loops
A loop's time complexity where a fixed amount is either added to or subtracted from the variable
int j=1;
do
{
j++;
}
While (j<=n);
Whereas
j is a loop variable in this instance.
n: The number of times the loop should be run.
In the situation above, the loop is run 'n' times. Consequently, this loop's temporal complexity is O(n).
A loop's time complexity where a fixed amount is either multiplied to or divided from the variable
do while loop
int j=1;
do
{
j = j*K;
}
While(j<=n);
whereas
j is a loop variable in this instance.
n: The number of times the loop should be run.
K is the constant in the above instance
In the situation above, the loop is run 'n' times. Consequently, this loop's temporal complexity is O(logn).
A nested loop's time complexity
do while loop
int i=0;
do
{
do
{
int j =0;
j++;
}while(j<=i);
i++;
}while(i<=n-1);
Whereas
i is an outer loop variable in this instance.
j is a variable used inside a loop.
n is the number of times the loop should be run
In this instance, the inner loop is executed 'n' times during each iteration of i. The number of times the innermost statement must be executed determines how long the loop will take to complete.
The complexity of time is given as O (n2).
The time complexity for infinite loop
The infinite loop is run "infinitely" many times. As a result, an infinite loop has no "algorithm time complexity."
The time complexity for other loops
When there are several loops:
int i=1;
do
{
i++;
}while(i<=a);
int j=1;
do
{
j++;
}while(j<=b);
whereas
The total time complexity of all loops is equal to the sum of their individual time difficulties.
Therefore, the time complexity equals O(a)+O(b)
Methods to reduce the time complexity
We find the idea of optimization while working on any Java application. It is essential that the code we write is not only clear and error-free but also optimized, meaning that the amount of time it takes to run should be within the predetermined range. To accomplish this, we must consult the Java coding standards and check our code to ensure that it complies
Avoiding the long or lengthy methods
The techniques used should be concise and focused on a single feature. When techniques are too complex and take up too much processing time, memory and CPU time are used up during execution. Try to divide the approaches into smaller ones at logical transitions.
Reduce the number of if-else statements.
The program makes the decisions via conditional statements. Avoid using conditional statements excessively. The performance will be impacted if we use too many conditional if-else statements since JVM will need to compare the conditions. If your business logic contains too many criteria, try grouping them to provide a boolean result that can be used in the if statement. Additionally, if possible, we can consider substituting a switch statement for several if-else statements. Performance-wise, switch statements outperform if-else statements.
Avoid Concatenating String Objects With Strings
Since strings are objects of the immutable class, they cannot be reused.We have two options in this situation: StringBuilder or StringBuffer, with the former being preferred due to its performance advantage resulting from non-synchronized methods.
Using primitive data types
Since primitive type data is saved on stack memory and object data is stored on heap memory, using primitive types over objects is advantageous. Primitive types can be used in place of objects wherever possible since data access from stack memory is quicker than from heap memory.
Not using the big decimal class
We are aware that the BigDecimal class offers precise accuracy for decimal values.When performing calculations, BigDecimal consumes a lot more memory over long or double.
avoiding the Creation of large objects frequently
While being created, these items used a lot of resources. The performance of the application would be severely hampered by the generation of these objects due to increased memory utilization. Wherever possible, we should clone the object rather than produce a new one by using the Singleton technique to build a single instance of the object and reuse it as needed
We can reduce the time complexity in java using the input-output methods
The I/O methods include:
- Scanner class
- BufferedReader class
- User-defined FastReader Class
- Reader Class
Using Scanner class
import java.io.*;
import java.util.Scanner;
class Demo
{
public static void main(String args[])
{
Scanner sc = new sc(System.in);
System.out.println("Enter the number: ");
int n = sc.nextInt();
System.out.println("Using nextInt(): " + data1);
sc.close();
}
}
Using BufferedReader class
import java.io.*;
public class Demo
{
public static void main(String args[])throws Exception{
FileReaderfr=new FileReader("D:\\testout.txt");
BufferedReaderbr=new BufferedReader(fr);
int i;
while((i=br.read())!=-1){
System.out.print((char)i);
}
br.close();
fr.close();
}
}
Using Reader Class
import java.io.Reader;
import java.io.FileReader;
class Demo
{
public static void main(String args[])
{
char[] array = new char[200];
try
{
Reader input = new FileReader("input.txt");
System.out.println("data stream? " + input.ready());
input.read(array);
System.out.println("Data in the stream:");
System.out.println(array);
input.close();
}
catch(Exception e)
{
e.getStackTrace();
}
}
}