We use loop for repeating a piece of code multiple times. So optimizing anything inside the loop body will have a good impact in overall performance.
Let’s see some of the good practices while dealing with the loop in java:
1. Method calls are very costly .Hence avoid calling methods from loop body
2. When you want to copy one array content to another, Instead of doing in the loop use System.arraycopy()
Example :
Below code is for copying contents of arrayA to arrayB
System.arraycopy(arrayA, 0, arrayB, 0, arrayA.length);
It is always better than,
for(int i = 0 ; i < arrayA.length; i ++)
{
arrayB[i] = arrayA[i];
}
3. Use int as index variable instead of other number data types
for(int i = 0 ; i < 1000; i ++);
It is always better than
for(long i = 0 ; i < 1000; i ++);
4. Avoid using method calls to find the loop termination condition
Example :
You have an arraylist and you want to do some operation as many times as the arrayList size
int size = al.size();
for(int i = 0 ; i < size ; i ++)
{
//Loop body
}
It is always better than
for(int i = 0; i < al.size(); i ++)
{
// Loop body
}
5. Try to avoid accessing array elements n loop .It is efficient to access variables.
6. Avoid Exception handling in loop
Leave a Reply