1

I want to optimize the code For comparison between 3 Lists. I don't want to use loop in code.

for(AttachmentWrapper aw : AttachmentResult) {
        for(GooglePrintJobs__c gpj : GooglePrintJobs) {
            if(aw.getAttachment().id == gpj.AttachmentID__c) {
                for(ffhttp_GoogleCloudPrintModelJob gcpmjs : GoogleCloudPrintModelJobs){
                    if(gcpmjs.id == gpj.GooglePrintJobID__c){
                        aw.setStatus(gcpmjs.status);
                    }
                }
            }
        }
    }

Please help me. is there any chance to optimize the code.

6
  • 3
    You don't, use Maps
    – EricSSH
    Commented Sep 2, 2016 at 18:17
  • 1
    Wow that is some awful naming. Quick, what is a gcpmjs? Maybe consider just naming it model.
    – Adrian Larson
    Commented Sep 2, 2016 at 18:21
  • 2
    @Adrian -- I would have used gcpmjs ;-)
    – cropredy
    Commented Sep 2, 2016 at 18:44
  • Guessing "Google Cloud Print Model Job Single" or "Google Cloud Print Model Job(s)"
    – Eric
    Commented Sep 2, 2016 at 19:11
  • And what are the 3 lists or values from the 3 lists you are comparing? From the code the loops are using 3 completely different objects...If you are just getting IDs from each of those objects then use maps as EricSSH suggests
    – Eric
    Commented Sep 2, 2016 at 19:14

1 Answer 1

6

As it's suggested in the comments, Maps it's a good way to improve code based on for loops.

Map<String, GooglePrintJobs__c> gpjs = new Map<String, GooglePrintJobs__c>();
Map<String, ffhttp_GoogleCloudPrintModelJob> gcpmjss  = new Map<String, ffhttp_GoogleCloudPrintModelJob>();

for(GooglePrintJobs__c gpj : GooglePrintJobs) {
    gpjs.put(gpj.AttachmentID__c, gpj);
}
for(ffhttp_GoogleCloudPrintModelJob gcpmjs : GoogleCloudPrintModelJobs) {
    gcpmjss.put(gcpmjs.id, gcpmjs);
}

for(AttachmentWrapper aw : AttachmentResult) {
    GooglePrintJobs__c gpj = gpjs.get(aw.getAttachment().id);
    ffhttp_GoogleCloudPrintModelJob gcpmjs = gcpmjss.get(gpj.GooglePrintJobID__c);
    aw.setStatus(gcpmjs.status);
}

I did a small POC to verify if actually this improvement makes any difference and it does:

Long startList = System.now().getTime();
for (Integer a : ints1) {
    for (Integer b: ints2) {
        if (a == b){
            //found!
        }
    }
}
Long endList = System.now().getTime();

VS

Long startMap = System.now().getTime();
for (Integer a : ints1) {
    Integer b = intsMap.get(a);
}
Long endMap = System.now().getTime();

Results:

System.debug('List: ' + (endList - startList));  // |DEBUG|List: 3430 (Tested with 700 different ints)
System.debug('Map: ' + (endMap - startMap));     // |DEBUG|Map: 7 (Tested with 700 different ints)

You must log in to answer this question.

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