[SalesForce] best practice for object initialization

What is the best approach from below two for initializing an object instance while creation in a loop.

for(string str: stringList){ 
                        //create obj records 
                        object__c obj = new object__c();                        
                             obj.name = str.name;                  
                            InsertRecords.add(obj);   
                        }

second:

//create obj records 
                     object__c obj = new object__c();  
    for(string str: stringList){ 

            obj.name = str.name;                  
            InsertRecords.add(obj);   
       }

Best Answer

//create obj records 
object__c obj = new object__c();  
for(string str: stringList){ 
    obj.name = str.name;                  
    InsertRecords.add(obj);   
}

This creates just one instance of a record, but will be in the list more than once. The result will be a "duplicate record in list" error when you try to insert it. Also, a noted in the comments, if you just try to use the records, they'll all mirror each other. This will also cause problems if you're trying to build a list for, say, editing in a Visualforce page, because the results will be unpredictable. In other words, just don't do this.


for(string str: stringList){ 
    //create obj records 
    object__c obj = new object__c();                        
    obj.name = str.name;                  
    InsertRecords.add(obj);   
}

This is a correct way to do this, because you're creating one instance per value. However, it's incredibly inefficient, and becomes increasingly so for each additional field you need to set.


Instead, skip the temporary entirely, and add it directly to the list:

for(String value: stringList) {
    insertRecords.add(new Object__c(Name=value));
}

Assigning a value to a field in the SObject constructor is at least twice as fast, which means that you'll gain more benefit the more fields you assign at once. Also, if you don't need the temporary variable, you'll gain something like a 50% speed boost compared to using the temporary.

Related Topic