SOQL for loops

SOQL For Loops

SOQL for loops retrieve all sObjects, using efficient chunking with calls to the query and queryMore methods of SOAP API. Developers can avoid the limit on heap size by using a SOQL for…

As we can read in the documentation:

SOQL for loops retrieve all sObjects, using efficient chunking with calls to the query and queryMore methods of SOAP API. Developers can avoid the limit on heap size by using a SOQL for loop to process query results that return multiple records.

It’s worth mentioning that the approach can increase the total heap size.

Don't do this
List<Account> accounts = [SELECT Id, Name FROM Account];

for (Account acc : accounts) {
    // ...
}
Do this
for (Account acc : [SELECT Id, Name FROM Account]) {
    // ...
}

Text and code were extracted from the original slide. Plain-text version of the whole catalog