function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Nithesh NNithesh N 

Alternative to Nested Apex iterations ?

Its a well known fact that loops inside of loops, especially nested more than once, can be catastrophic for CPU performance. 
for(Integer a = 1; a <= 100; a++) {
    for(Integer b = 1; b <= 100; b++) {
        for(Integer c = 1; c <= 100; c++) {
            System.debug(a * b * c);
        }
    }
}
Is there any alternative algorithm to avoid  nested loops?
I want to know the best practices to avoid the nested loop scenarios if possible.
Thanks !!

 
Best Answer chosen by Nithesh N
Mradula Jain 5Mradula Jain 5
You can iterate one for loop and for rest two use MAP. MAP is key and value pair so you can compare your fields and that would avoid the nested loops. Please go through below link to know how to use MAP.
https://salesforce.stackexchange.com/questions/80387/avoid-nested-for-loop-while-iterating-mapinteger-setinteger
 

All Answers

Amit Singh 1Amit Singh 1
Nitesh,

The best practice is that to use Collection to avoid the Nested for loop and also using the Collection SOQL inside for loop can be avoid. If there is no way where we can minimise the Nested for loop then we need to use Nested For Loop.

Let me know the outcomes.
Thanks,
AMit Singh
Mradula Jain 5Mradula Jain 5
You can iterate one for loop and for rest two use MAP. MAP is key and value pair so you can compare your fields and that would avoid the nested loops. Please go through below link to know how to use MAP.
https://salesforce.stackexchange.com/questions/80387/avoid-nested-for-loop-while-iterating-mapinteger-setinteger
 
This was selected as the best answer