Hello Salesforce Devs!
I'm just curious to know which one of the below has better performance when looking up child records.
For example, finding number of cases on an account:
#1: List<Account> acctList = [SELECT ID,(SELECT ID FROM Cases) FROM Account LIMIT 1];
Integer count = 0;
for(Account acct : acctList) {
count = acct.cases.size();
}
System.debug(count);
#2: List<Account> acctList = [SELECT ID FROM Account LIMIT 1];
Set<Id> acctIds = new Set<Id>();
for(Account acct : acctList) {
acctIds.add(acct.Id);
}
List<Case> caseList = [SELECT ID FROM Case WHERE accountId in: acctIds];
Integer count = caseList.size();
System.debug(count);
My gut tells me that #2 is faster because it has O(n), but since I don't know how #1 works in the background I'm not 100%. In case of #1, would the time complexity to search for child object records come out to O(n^2)?
In terms of space complexity, #1 would be optimal since it uses only one SOQL and using less query matters in Salesforce world.
By considering both time and space complexity, which way would you construct your code if they are not completely the same? Thanks for your time reading/answering this in advance :)