Is there any performance difference between:
Contact con = new Contact();
con.Id = conId;
con.AccountRoles__c = newRole;
... and...
Contact con = new Contact(
Id = conId,
AccountRoles__c = newRole
);
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It only takes a minute to sign up.
Sign up to join this communityIs there any performance difference between:
Contact con = new Contact();
con.Id = conId;
con.AccountRoles__c = newRole;
... and...
Contact con = new Contact(
Id = conId,
AccountRoles__c = newRole
);
The second form is approximately twice as fast. I wrote a quick test to prove this. 10,000x records with two fields takes about 250ms using the SObject constructor, and 500ms by assigning actual fields.
I presume the difference comes from house-keeping that has to occur between each full statement (e.g. checking for governor limits, garbage collection, etc), plus the fact that all of the memory needed can be allocated up-front instead of having to grab memory from the heap multiple times.
This probably doesn't matter for small projects, but if you're using the first form often and your project seems slow, this is a viable optimization. This behavior is also true for Id[] v = new Id[0]; for(...) { v.add(...); }
versus Id[] v = new Id[] { ... };
.
For example, an array of three elements takes 750ms for 10,000 allocations, but 1500ms+ for creating the array and then using add.
Note that the total heap usage is otherwise identical, but it's a major CPU hit.