[SalesForce] Efficiency of List.size() > 0 vs. !List.isEmpty()

Anyone have any data to support a claim for which of the following two expressions is more efficient (meaning faster)? The use case is determining whether a List is empty to inform an auxiliary method such as hasErrors().

Option 1: Use List.isEmpty()

public static Boolean hasErrors() {

    // Assume getErrors() returns a List object
    return !getErrors().isEmpty();
}

While semantically this approach makes a lot of sense, I wonder whether the ! operator has any material impact on the method's performance.

Option 2: Use List.size()

public static Boolean hasErrors() {

    // Assume getErrors() returns a List object
    return getErrors().size() > 0;
}

The questions raised by this alternative approach are: Is List.size() inherently faster than List.isEmpty()? And how does the performance of the greater than (>) operator compare to that of the negation (!) operator?

Best Answer

UPDATE, I now cover all four cases and tested in a different org so the raw numbers are different.

I agree that isEmpty is superior from a readability perspective. However, out of curiosity I ran each scenario 50,000 times. The size method took .02334 seconds on average , whereas the isEmpty method took .02139 seconds on average. That is a difference of around 9%. The difference appears negligible.

Here is my methodology, perhaps less elegant than Mr. Ballinger's.

List<String> strings = new List<String>();
for (Integer i = 0; i < 10000; i++) { strings.add(String.valueOf(i)); }
Datetime start = Datetime.now();
for (Integer i = 0; i < 50000; i++)
{
    // use one of the following:
    // Boolean isNotEmpty = !strings.isEmpty();
    // yields 1092
    // Boolean isNotEmpty = strings.size() > 0;
    // yields 1085
    // Boolean isEmpty = strings.isEmpty();
    // yields 1047
    // Boolean isEmpty = strings.size() == 0
    // yields 1249
}
Datetime stop = Datetime.now();
system.debug(stop.getTime() - start.getTime());

// (1092 + 1047) / 100,000 = .02139
// (1085 + 1249) / 100,000 = .02334
Related Topic