Apr 11, 2011

Saving Script Statements

Hi All,


Many of you must aware of this but would like to share with all.


Generally when we write a apex code we don't focus on saving the script statements, but when we are working with code in bulk then we should take care of our script statements to reduce the processing of our code and also to avoid the governor limit of 200,000.


Now if we want to fetch ids of all account from my organisation, one generally use this code:

//Fetching all accounts
List<account> accObj = [select Id from account limit 50000] ;

//Creating set of all account Ids
List<id> accIds = new List<id>() ;

//Fetching Account ids
for(Account acc : accObj)
{
 accIds.add(acc) ;
}
//Now we use this list of account ids in other queries




Now if the query will return 50000 records then for loop will execute 50000 script statements. Now to avoid this we can simply write:

//Fetching all account in map
Map<id,account> aMap = new Map<id,account>([Select Id,Name from Account limit 50000]);

//Creating list of accounts
List<account> accList = aMap.values() ;

//Creating set of ids
Set<id> accIds = aMap.keySet() ;




Now if any query returns sObject as return type then also we can use this approach by typecasting it like this :

//Your dynamic query
String accountDynamicQuery = 'select id from account limit 50000' ;

//Typecasting it to map
Map<id,account> mapAcc = new Map<id,account>((List<account>)Database.query(accountDynamicQuery));




Now when we insert a object lets say if we want to insert account with values in some fields then we write:

Account accObj = new Account();
accObj.Name = 'Test' ;
accObj.Fax = '123445657' ;
accObj.Phone = '123456789' ;
insert accObj ;



Instead of this we can write this to save our script statements:

Account accObj = new Account(Name = 'Test' , Fax = '12345657' , Phone = '123456789') ;
insert accObj ;



Cheers

1 comment:

  1. how does this applies to situation like this:

    update a start-end range to Product first (around 1000+ records);
    then use this start-end range to update Serial No. records of corresponding Product (around 10000 records)

    ReplyDelete