112

In parts of my code I have DML statements with an if around to only do the DML if the list is not empty:

if( !recordsToUpdate.isEmpty() ) {
   update recordsToUpdate;
}

Couldn't I just write?

update recordsToUpdate;

Or would I provoke errors or needlessly consumed limits by doing that?

107

Good question, I've never considered it before...

i've just assumed the platform will play fair and I'm pleased to find it does!

System.debug('Before DmlStatements : ' + Limits.getLimitDmlStatements());
System.debug('Before DmlRows : ' + Limits.getDmlRows());
insert new List<Account>();
System.debug('After DmlStatements : ' + Limits.getLimitDmlStatements());
System.debug('After DmlRows : ' + Limits.getDmlRows());

Results in a successful completion and confirmation of no governor usage.

09:00:14.185 (5185191000)|USER_DEBUG|[1]|DEBUG|Before DmlStatements : 150

09:00:14.185 (5185303000)|USER_DEBUG|[2]|DEBUG|Before DmlRows : 0

09:00:14.185 (5185553000)|SYSTEM_CONSTRUCTOR_ENTRY|[3]|()

09:00:14.185 (5185606000)|SYSTEM_CONSTRUCTOR_EXIT|[3]|()

09:00:14.185 (5185933000)|USER_DEBUG|[4]|DEBUG|After DmlStatements : 150

09:00:14.186 (5186055000)|USER_DEBUG|[5]|DEBUG|After DmlRows : 0

| improve this answer | |
  • 2
    That is a great question. Like you, I had never considered it before and always just threw in the check for non empty lists. Very interesting find, so in theory are we just wasting a line of code by checking the list isn't empty? Is there any other advantage to checking before the insert? – Chris Duncombe Nov 8 '13 at 12:25
  • 2
    None that I can think, i think its a reasonable contractual assumption that if a method (or operation in this case) takes a collection, it should a) not fail and b) use very minimal resources to execute if the list is empty. It seems in this case the SF developers are complying with this design assumption. :) – Andrew Fawcett Nov 8 '13 at 13:01
  • 8
    Note: Historically, empty lists did consume governor limits, which is why so many developers used the if-not-empty syntax. After this was fixed, a lot of old code, blog posts, etc were never updated. As a very small aside, the DML statement itself performs a if-not-empty check, which means that if a developer does so, the effect is the list is checked twice to see if it's empty, wasting a few milliseconds of CPU time. It's not a significant amount, but the point is that writing if-not-empty results in wasted code and CPU time. It has no upside. – sfdcfox Jul 11 '19 at 20:11

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