1

Two objects Opportunity and Asset. Asset object has a lookup field to Opportunity i.e Asset is the child and Opportunity is the parent.

Now say i need to perform some operation on the Opportunity record based on the values from its related child Asset records.

Note: we can get list of Opportunites OR the list of Assets as input.

one way is to write nested for loop something like (if input is Opportunities)

Approach #1

Integer value;
for(Opportunity op : opptyList){
 for(Asset as : op.assetlookup__r){
  value = value + as.somefieldvalue;
}
op.updatingfield = value;
}

Other way is (if input is Assets)

Approach #2

for(Asset as : assetList){
 // use Map asset id as key and the field value to achieve wt we need to 
}

Approach #1 has nested for loop which according to coding principles is a bad design.

Approach #2 is a simple single for loop.

But the number of times both Approach #1 and Approach #2 will run seems to same. SO in these sought of situations does a nested for loop or a single loop both same in terms of performance?

Pardon the clarity on the given examples, they are just to give some idea

1 Answer 1

3

Approach #1 has nested for loop which according to coding principles is a bad design.

This is an incorrect understanding of the "no nested loops" rule of thumb. There are times when a nested loop is perfectly appropriate. Your example code is a perfectly acceptable use of nested loops in programming.

The problem loops are those that cause exponential processing:

Account[] accounts = [SELECT Id FROM Account];
Contact[] contacts = [SELECT AccountId FROM Contact];
for(Account accountRecord: accounts) {
    for(Contact contactRecord: contacts) {
         if(accountRecord.Id != contactRecord.AccountId) {
             continue;
         }
         // rest of logic
    }
}

There is nothing wrong with using nested loops in the manner you've described, so long as it makes sense for the code. The execution time scales (approximately) linearly when using nested loops as in your first example, but exponentially when done as demonstrated in the code block above.


Nested loops do have a performance penalty, as each inner loop has to create an iterator (internally) to support the inner loops. As near as I can tell, the performance penalty is approximately 1ms for each time the inner loop has to start. This means that if you have an opportunity with 50 assets, the penalty would be 1ms, but if you have 20 opportunities with 50 assets each, the penalty would be 20ms (approximately). As you can see, you would need to be dealing with thousands of records before the penalty became crippling. If it makes sense for your algorithm (e.g. easier to read, avoids the use of a map, etc), feel free to use the first method.

1
  • excellent, thanks
    – steamyfire
    Commented Oct 27, 2019 at 11:04

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .