Saving Script Statements | Techila
2357
single,single-post,postid-2357,single-format-standard,ajax_updown_fade,page_not_loaded,,qode_grid_1300,footer_responsive_adv,hide_top_bar_on_mobile_header,qode-content-sidebar-responsive,qode-theme-ver-9.4.2,bridge,wpb-js-composer js-comp-ver-4.12,vc_responsive
 

Saving Script Statements

SAVING SCRIPT STATEMENTS

Saving Script Statements

Generally when we write an 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 organization, 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 let’s 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 ;

Courtesy:  http://forceguru.blogspot.in/2011/04/saving-script-statements.html
https://ajomonjoseph.files.wordpress.com/2016/05/code.png?w=984

“Explore – Techila Global Services, A Salesforce development company”

Author: techila

No Comments

Post A Comment