• Andreas Wolf 25
  • NEWBIE
  • -1 Points
  • Member since 2017

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 1
    Replies
Hi,

I would like to understand the way 'states' are retained across batches while using Database.Stateful.

Example, If I am using 'totalSum'  as variable to be maintained across batches, then I could do one of the following.  Which one of below is more optimal? does the SF makes sure that the 'serialization of execution' is done only when the Line 2 in option 2 used about to be executed?, 
if the serialization is across all the body of execution(), then option-1 and option-2 does not look too different.
 
//Option 1

execute (scope) {
   foreach(myObject__c obj: scope) {
       totalSum += obj.field_to_sum__c; //<== Line 1
   }
}
 
//Option 2

execute (scope) {
   Integer localSum = 0;
   foreach(myObject__c obj: scope) {
       localSum += obj.field_to_sum__c;
   }

 totalSum += localSum;  //<== Line 2
}