Basics
Apex Loops
Loop Structures
Apex loops use for and while with governor limit awareness.
Introduction to Loops in Apex
Loops are a fundamental concept in programming that allow you to execute a block of code repeatedly. In Apex, the two primary loop constructs are for and while loops. Understanding how these loops work, particularly in the context of Salesforce's governor limits, is crucial for writing efficient code.
For Loop in Apex
The for loop in Apex is used to iterate over collections or execute a block of code a set number of times. It is particularly useful when you know in advance how many times you want the loop to run.
In this example, the loop will execute 10 times, outputting the current iteration number to the debug log each time. The loop begins with Integer i = 0
, continues while i < 10
, and increments i
by 1 each iteration.
While Loop in Apex
The while loop is used when the number of iterations is not known beforehand. The loop will continue to execute as long as the specified condition evaluates to true.
This example demonstrates a while
loop that runs five times. The loop continues until the condition count < 5
is no longer true, incrementing count
each iteration.
Governor Limits Awareness
Salesforce imposes governor limits to ensure efficient use of resources. When using loops in Apex, it's important to be aware of these limits, such as the maximum number of SOQL queries, DML statements, and CPU time allowed per transaction.
For example, consider using a SOQL
query inside a loop. This can quickly hit query limits if not handled properly. Instead, use SOQL
queries outside loops when possible and process the results using collections.
In the efficient example, the SOQL
query is executed once, and the results are stored in a list. The loop then processes each account in the list, minimizing resource usage and staying within governor limits.