Currently we have a few nested for loops in our codebase that are doing what is mentioned in the question, but if we data load a large amount of records we run into CPU time errors. I am wanting to optimize as much as possible by eliminating these nested for loops. How can I perform operations on each opportunity in a list of accounts efficiently? An example of the pattern I'm trying to change is below.

List<account> accounts = [
               SELECT id, Name, (SELECT id, StageName, CloseDate, OwnerId from Opportunities)
                FROM Account
                WHERE id IN :accountIds

for (Account acc : accounts) {
            for (opportunity opp : acc.opportunities) {
                //Opportunity operations here;
        } //Want to optimize this logic

Nested loops are not inherently evil, and are required if you're working on a nested structure like this.

You could rewrite this particular query to be on Opportunity instead of Account, but CPU limit issues usually run deeper than a simple nested loop or two.

About the only answer I can give you here is that you need to spend a fair amount of time profiling your code so you can accurately characterize the overall performance, and identify the problem areas (which methods are being called most often? which methods consume the most CPU time/queries/etc...?)

Turning up the debug log levels for the Apex category, and making use of the "Analysis" perspective in the dev console (With a debug log open in the dev console: Test -> Switch Perspective -> Analysis) will give you additional buttons and panels to play around with that should help you gather more information.


You could try querying the Opportunity table like so.

List<Opportunity> opp = [Select Id From Opportunity Where 
    AccountId IN (Select Id From Account Where Id = :accountIds)];

Otherwise if you are running into heap errors you might need to optimize your code before and after the query or move your code into batch.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.