Optimize Count = 0 to use List.Empty instead
38
Views
1
Comments
New
Backend

I have seen countless times the pattern "GetEmployees.Count <> 0" (or similar comparisons) to check if a query returned empty or not.

The problem with the above condition is that it requires the platform to execute an additional query to calculate the value of Count. However, the precise value of Count is not important in this case, it's only important whether it's 0 or not. This can be achieved with better performance by executing the query and checking the value of List.Empty - if false it means Count <> 0, if true it means Count = 0.

The optimization should be done automatically to boost performance especially on large tables.

It can be applied safely if:

* The only usages of the Count happen in a direct comparison with the literal 0.

* The Start Index of the query at runtime is 0 (in case of a screen aggregate).

* Debugger is not attached.

These conditions are met in a common enough scenario, when displaying a blank slate when a list is empty. Another scenario in logic is to check whether some relationship is empty, to determine whether to apply some business rule or not (e.g. don't delete Department if it has Employees).

When the conditions apply, the platform can return Count = 0 if List.Empty, or Count = 1 if not List.Empty.

100% agree