Activity Forums Salesforce® Discussions Difference between list.Size() > 0 vs list != null vs list.IsEmpty() in Salesforce?

  • Mohit

    Member
    December 15, 2016 at 8:04 am

    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

  • Ashley

    Member
    December 15, 2016 at 9:22 am

    Thanks Mohit. Does it mean list.Size() > 0 and list.IsEmpty() are same, and can be used interchangeably?

  • William Alexander

    Member
    January 31, 2020 at 8:27 pm

    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.

Popular Salesforce Blogs

Popular Salesforce Videos