If I have a for loop that loops through results from a database query, is the single record a reference or copied value?

The reason I ask is because I am attempting to update these records, but would it be better to update the whole array, or each one individually?

For example, which option is the better way to update multiple objects:

// Option 1
for (Object__c obj: objects) {
    obj.name = "new_name";
    update obj;

// Option 2 (possibility depending if "obj" is referenced or not)
for (Object__c obj: objects) {
    obj.name = "new_name";
update objects;

// Option 3 (same as Option 2, but different access method)
for (Integer i = 0; i < objects.size(); i++) {
    objects[I] = "new_name";
update objects;

I guess, basically what I'm asking is if Option 2 and Option 3 do the same thing? Or is the better practice option 1?

  • @Himanshu just a friendly reminder, comments are for clarification of the question, not answers. – sfdcfox Jan 29 '19 at 20:47

Objects are passed by reference.

Option 1 is Bad because it is un-bulkified. That pattern will rapidly chew through your slim allotment of 150 DML statements per transaction, yielding a LimitException.

Options 2 and 3 are largely equivalent, with 2 being more idiomatic. The integer loop variable is extraneous unless you have some other need to have access to the loop index.

Both 2 and 3 are effectively bulkified, meaning your code will be more performant, all else being equal, and will have much lower limits risk. It's important to note that limits still apply to bulkified code, but you'll be consuming them at a much more sustainable rate. You'll use only one DML statement in these options, although you'll still use N DML rows for N records - but the row limit is 10,000, rather than 150!

(Option 3 is missing the .Name, but I don't think that's material to your example).


We can only do 150 DML statements in 1 transaction. If you are trying to insert 1000 records using option 1, The code will break with LIMITS Exception. Check DML limits . Doing DML and SOQL in for loops is RED FLAG. Very bad in SF environment.

Option 2 and 3 are better than option 1.

Performance wise option 2 will be better as you are not manually accessing array via Index and letting salesforce do that job for you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.