Code Optimization : Find size inside loop

Motivation

keytakeaways

  • here we will see the performance improve when we find the size of the list inside for loop or outside for loop.
1.Finding size of the list inside for loop ?
for(int i = 0; i < spr.getResults().size(); i++) {  
    HashMap results = (HashMap) spr.getResults().get(i);
  • in the above mentioned code you can see the number of time the code is ran the size of the list is calculated , here in our case it is 6k but this can be much higher so in that case the size is calculated n times imageine you are doing this for 1Lakh records

  • Remediation

    1. Calculate the size outside for loop and then use it traverse the list
int sizeOfAccountList= spr.getResults().size();
for(int i = 0; i < sizeOfAccountList; i++) {  
    HashMap results = (HashMap) spr.getResults().get(i);
  • lets understand how much time we have saved by doing this

Before Optimization

  • Time taken for 1 million records for this case is 13 milliseconds before optimization

After Optimization

  • Time Taken : 8 milliseconds

Code Afterwards

import java.util.*;

class Main {

    public static void main(String args[]) {

        //creating a list of size 1 million records

        List<Integer> parentList= new ArrayList<>();

        List<Integer> childList=new ArrayList<>();

        for(int i=0;i<1000000;i++) {

            parentList.add(i);

            childList.add(i*2);

        }

        int sum=0;

        long starttime=System.currentTimeMillis();

        System.out.println(starttime);

        int parentListSize=parentList.size();

        for(int i=0;i<parentListSize;i++) {

            sum+=i;

        }

        System.out.println("Time taken to complete "+ (System.currentTimeMillis() - starttime));

    }

}