function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
BroncoBoyBroncoBoy 

Best Practices & Efficiency Retrieving Data from Map or Lists

Trying to retrieve several user Ids and assign them to variables of Id type - but I am generally curious as to the best approach here - so I'm looking for opinions.  Thanks in advance!

In my view C) works but only if the SOQL returns records, otherwise you get a 'now rows returned' error.  A)  A works but again will return a "list out of bounds error if the SOQL returns 0 records  B) seems the best to me because if there is no key it simply returns null...but I'd like to hear your opinions.

So, which approach is the more efficient - which one is the best practice below, A, B or C (or Other) - is B the best? 
A)
list<User> jnldGenericId = [SELECT Id FROM User WHERE Name = '1' LIMIT 1];
list<User> rbdGenericId = [SELECT Id FROM User WHERE Name = '2' LIMIT 1];
list<User> imgGenericId = [SELECT Id FROM User WHERE Name = '3' LIMIT 1];
list<User> cclGenericId = [SELECT Id FROM User WHERE Name = '4' LIMIT 1];

Id Owner1 = rbdGenericId[0].Id;
Id Owner2 = imgGenericId[0].Id;
Id Owner3 = cclGenericId[0].Id;
Id Owner4 = jnldGenericId[0].Id;

OR

B)
map<String, Id> userNameIdMap = new map<String, Id>();

for(user u : [SELECT Id FROM User WHERE Name = '1' OR Name = '2' OR  Name = '3' OR Name = '4'])
{
    userNameIdMap.put(u.Name, u.Id);
}

Id Owner1 = userNameIdMap.get('1');
Id Owner2= userNameIdMap.get('2');
Id Owner3 = userNameIdMap.get('3');
Id Owner4= userNameIdMap.get('4');

OR

C)
Id Owner1= [SELECT Id FROM User WHERE Name = '1' LIMIT 1].Id;
Id Owner2 = [SELECT Id FROM User WHERE Name = '2' LIMIT 1].Id;
Id Owner3 = [SELECT Id FROM User WHERE Name = '3' LIMIT 1].Id;
Id Owner4 = [SELECT Id FROM User WHERE Name = '4' LIMIT 1].Id;
 
Best Answer chosen by BroncoBoy
bob_buzzardbob_buzzard
B is best practice, as you are only executing a single SOQL query, and you can test the result of the get rather than encountering an error if there are no records matching the name. I'd also expect it to be the most efficient as the cost of 3 further trips to query the database would exceed the cost of iterating the results to store in a map and then executing 4 gets.

All Answers

bob_buzzardbob_buzzard
B is best practice, as you are only executing a single SOQL query, and you can test the result of the get rather than encountering an error if there are no records matching the name. I'd also expect it to be the most efficient as the cost of 3 further trips to query the database would exceed the cost of iterating the results to store in a map and then executing 4 gets.
This was selected as the best answer
BroncoBoyBroncoBoy
Perfect, thank you!