Activity › Forums › Salesforce® Discussions › Difference between list.Size() > 0 vs list != null vs list.IsEmpty() in Salesforce?
Tagged: Datalist, Help & Training, List, Salesforce Apex, Salesforce Development, Salesforce List, Salesforce SOQL, String List
-
Difference between list.Size() > 0 vs list != null vs list.IsEmpty() in Salesforce?
Posted by Ashley on December 14, 2016 at 11:57 PMWhat is the different between list.Size() > 0 vs list != null vs list.IsEmpty()?
William Alexander Aldana Carvajal replied 6 years, 3 months ago 3 Members · 3 Replies -
3 Replies
-
Hi Ashley,
The List.Size() > 0 will check whether the list has any record in it or not.
The List!=null will be use full when you have not initialize the list. It is not helpfull to check the whether the list has any record or not. This is a waste of CPU time, because (a) records will never be null, and (b) iterating over an empty list is acceptable
And List.isEmpty() then it also check whether the list has any record or not.
for Example:-
Account[] records = [SELECT Id, Name, AccountNumber FROM Account];
if(records!=null && !records.isEmpty()) {
for(Account record: records) {
// Do Something Here
}
}Thanks
- [adinserter block='9']
-
Thanks Mohit. Does it mean list.Size() > 0 and list.IsEmpty() are same, and can be used interchangeably?
-
List.Size() is slow because needs to count all the elements in the collection.
List.IsEmpty() only checks zero position has value.
if you joins list != null and !list.IsEmpty() you will avoid possible null exceptions.
I’ve read the difference is approximately 10%. I have not checked it but has a sense
Log In to reply.