Loading
Scalability
ApexGuru Antipattern: Copying List or Set Elements Using a For Loop

ApexGuru Antipattern: Copying List or Set Elements Using a For Loop

Using a For loop to copy parts of a list or set takes more CPU time and can cause governor limit breaches, especially with large datasets. Instead, Apex provides the addAll() method to copy elements efficiently in a single operation, improving both performance and code clarity.

Scope

Detection and recommendation

Detection Example

The developer is manually iterating over attachmentPresentIdsCassic to copy each Id into attachmentPresentIds.

for (Id ids : attachmentPresentIdsCassic){
    attachmentPresentIds.add(ids);
}

Recommendation

The recommended fix replaces this manual loop with the built-in addAll() method, which copies the entire collection in one step.

attachmentPresentIds.addAll(attachmentPresentIdsCassic);
 
Загрузка
Salesforce Help | Article