Considering the following test class:
@IsTest
private class ProfilingTest {
private static String TEST_STR = '';
public static testMethod void testForEachLoop(){
List<Account> accs = [SELECT Id, Name FROM Account LIMIT 5000];
for(Account acc : accs){
acc.Name += TEST_STR;
}
}
public static testMethod void testForLoop(){
List<Account> accs = [SELECT Id, Name FROM Account LIMIT 5000];
for(Integer i = 0; i < accs.size(); ++i){
accs[i].Name += TEST_STR;
}
}
public static testMethod void testImprovedForLoop(){
List<Account> accs = [SELECT Id, Name FROM Account LIMIT 5000];
Integer size = accs.size();
for(Integer i = 0; i < size; ++i){
accs[i].Name += TEST_STR;
}
}
public static testMethod void testWhileLoop(){
List<Account> accs = [SELECT Id, Name FROM Account LIMIT 5000];
Integer size = accs.size();
Integer i = 0;
while(i < size){
accs[i].Name += TEST_STR;
++i;
}
}
}
Is there a particular reason why standard for loop is faster in Apex than for-each loop? What I think is it may be because the 'i' knows which element to pick and for every iteration the size of the list gets smaller and smaller.
But I need some more explanation as why are we seeing huge performance advantage when using standard for loop ?
acc.Name += TEST_STR;
toaccs[index++].Name += TEST_STR;
in thetestForEachLoop
method with index defined outside the loop asInteger index=0
.