8

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
);
3
  • 4
    You could write a test to find out. The second form wins hands down on cleaner syntax.
    – Keith C
    Jun 19, 2015 at 23:22
  • Disagree on that. Especially if you go over 50 fields.
    – Adrian Larson
    Jun 20, 2015 at 1:49
  • 1
    @AdrianLarson With both laid out one assignment per line, the second still wins for me. Now the curly brackets...
    – Keith C
    Jun 20, 2015 at 9:27

1 Answer 1

12

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.

0

You must log in to answer this question.

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