+ Start a Discussion
Biswajit Nath 9Biswajit Nath 9 

Compare new and old values in apex without using double for loop

Hi All,

I am trying to optimize a code.
The code uses nested For loop to compare values from new trigger and old trigger. As a result, some time it hits the Apex CPU Time Limit error for a large volume of data.
I would like to ask if there is any better and efficient way to handle this situation.
Many thanks in advance!
 
Suraj Tripathi 47Suraj Tripathi 47
Hi Biswajit,

you can easily optimize your code by using map, store your old values into map and iterate over new trigger value 
and then fetch value from map, please preffer below code
 
public class AccountHelper{
public static void accUpdate(list<Account> newList,list<Account> oldList){

map<id,Account> accountMap = new map<id,Account>(oldList);

for(Account accObj:newList){
if(accountMap.ContainsKey(accObj.Id)){
Account acc =   accountMap.get(accObj.Id);
if(here you can compare values){

}
}
}

}
}

If you find your Solution then mark this as the best answer.

Thank you!

Regards,

Suraj Tripathi  

 
ravi soniravi soni
hi,
if you are working on trigger then simply you can get reference from below code for getting data.
use trigger.oldMap.get(acc.Id) and get old field value.

trigger.new => it 's return new data
trigger ActiveAccount on Account (before insert,before update) {
 if(account acc : trigger.new){
        if(acc.Name == trigger.oldMap.get(acc.Id).Name){
            system.debug('AccountName===> ' + acc.name);
        }
    }
	}

try above code and if it helps you ,don't forget to mark it as best answer.
Thank you
ravi soniravi soni
hi Biswajit,
did you try my solution. try it once and don't forget to mark it as best answer if it help you so that it can help to others in future.

Your one best mark give us motivation to working in this direction.
Thank you