
Fastest "For Loop" in Salesforce
Loops play a very important part in our Lives. Whenever we need to play over large sets of Data, we usually use For Loops. But have you ever made a thought how the way you write your For Loop affects your CPU Time?
Nope!!!!Okay Let me give you an overview on that. I have executed different kinds of For Loops each with the CPU Time spent for their Execution.
Now you can execute this Class ForLoopSpeed via Anonymous Window & checkout the Debug :
#### Time Spent
You will find out that WAY 3 is Fastest with 1 ms of Time Spent.
I have currently 16 contacts related to the Account 'Manpreet Singh' thats why the time differences are close.With an account with more no of Contacts you can see some more differentiating results.
If your Preference is using For Each Loop then you can go with the WAY 4.
Cheers!!!
Great Article.
In approach 3, I believe if we will store number of contacts in an integer variable and use that variable in for loop, instead of contacts.size(), then it should take even lesser time since for every cycle it needs not to check with contacts.size() ( unnecessary calculation)...