0

let me show you two different ways of updating a record I've stumbled upon:

Example 1:

List<ContentVersion> outs = new List<ContentVersion>();
List<ContentVersion> vers = [Select Id from ContentVersion where Custom_Field__c = 'ABC'];
for (ContentVersion ver : vers) {
            ContentVersion out = new ContentVersion(
                Id = ver.Id,
                Custom_Field__c = 'XYZ');
            outs.add(out);
        }
update outs;

Example 2:

List<ContentVersion> outs = new List<ContentVersion>();
List<ContentVersion> vers = [Select Id from ContentVersion where Custom_Field__c = 'ABC'];
for (ContentVersion ver : vers) {
            ver.Custom_Field__c = 'XYZ';
            outs.add(ver);
        }
update outs;

Could anyone explain to me if there is any difference and when to use the first technique and when the second one?

1 Answer 1

0

In the end, both approaches acccomplish the same thing (updating an existing record). In that respect, there is no appreciable difference.

Using the SObject constructor (the first approach you listed) to set fields is ever so slightly faster than using dot-notation, but you won't really see any difference until you're processing more records than can be DML'd in a single transaction.

Perhaps the most useful difference is that using the SObject constructor allows you to upade an object without the need to query for it.

ex.

// Let's say you're working on Opportunities as part of a trigger, and want to update
//   the related Accounts
Map<Id, Account> accountsToUpdate = new Map<Id, Account>();
for(Opportunity opp :trigger.new){
    Account relAccount = new Account(
        Id = opp.AccountId,
        Most_Recent_Updated_Opp__c = opp.Id
    );

    accountsToUpdate.put(relAccount.Id, relAccount);
}

update accountsToUpdate.values();

Queries are generally the governor limit that people run into first, so having a way to avoid performing queries is very helpful.

0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .