Saturday, August 27, 2011

Apex heap size too large And Too Many Script Statement in apex salesforce

Hi guys these kind of error I had faced many time because of the large data in organisations. When ever we process the number of records governor limit hit these kind of error.

Normally we queried the records like.
List<Account> lstAcc = [select Id,Name from Account];
for(Account Acc :lstAcc){
    //your code here     Running statement for each records. And Hitting the script statement limit
}
We can use this in another way by which we can escape two kind of error mentioned above.
We can do a SOQL inside the for loop something like this.
for(List<Account> lst :[select Id,Name from Account]){
     // Loop first statement having 200 records in single batch.
}
This way is only for when you are not tracing one by one object and making calculation. We can use this ways if we are adding all records in a new list .
for(List<Account> lst :[select Id,Name from Account]){
   newList.addall(lst);
}
Suppose we have 500 records to process the this loop will run max 3 time.

This line of code reducing the script statement because this structure make the batch of 200 record for a single statement. And This is also reducing the Apex Heap size.

Cheers..........................

4 comments:

  1. How, only 200 records are processed here? We are not using any batch apex. Kindly clarify if I missed anything.

    ReplyDelete
  2. No I dint had the limit of 200 lets say if your query returning 1000. It will chuck record in 200 size. and your loop will traverse 5 times only.

    ReplyDelete
  3. So what changes do we need to do, in the query, to break the number of records into 200 per batch. Please let me know.

    Thanks.

    ReplyDelete
  4. you want to process the record per 200 only use batch apex. Its just about to reducing heap and script statement.

    ReplyDelete