+ Start a Discussion
Anonymous123Anonymous123 

Memory allocation in apex class`

Hi,

 

Please look at the below 2 code snippets:

 1)  

public class selectedRecords {
public List<clsWrapper> accls=new List<clsWrapper>();

 

2)

public class selectedRecords {
public List<clsWrapper> accls{get;set;}
public List<clsWrapper> getAccounts(){
accls=new List<clsWrapper>();
if(accls==null && accls.size()==0){
for(Account a: [select id, Name from Account limit 10]){
accls.add(new clsWrapper(a));
}
}
return accls;
}


}

 mY question is: what is the differnence between allocating memory to the list in starting of class and inside getter ?

 

 

Best Answer chosen by Admin (Salesforce Developers) 
Karthik@TMCKarthik@TMC

In Snippet 1:

 

The Memory will be intialised only once, i.e. during Instantitation of Class(while creating objects for the class).

 

In Snippet 2:

 

The Memory will be intialised as many times you call the method. i.e. as many times as the component in VF calls that method which may be on hit of button,on component rerender,,,,etc.

 

 

All Answers

Karthik@TMCKarthik@TMC

In Snippet 1:

 

The Memory will be intialised only once, i.e. during Instantitation of Class(while creating objects for the class).

 

In Snippet 2:

 

The Memory will be intialised as many times you call the method. i.e. as many times as the component in VF calls that method which may be on hit of button,on component rerender,,,,etc.

 

 

This was selected as the best answer
Anonymous123Anonymous123

In the 1st scenario : what will happen if i refresh the page? will the memory allocation happen as many times i ll refresh the page 

Karthik@TMCKarthik@TMC
Refreshing the Page means calling a Constructor,then object re-creation is done. Then this Scenario falls under Snippet 1.
Anonymous123Anonymous123

Thanks a lot...