You are here:
ApexGuru Antipattern: Sorting in Apex
Sorting records in Apex code uses more central processing unit (CPU) time and can exceed governor limits. This is especially true for large datasets. Using Apex to sort can also lead to heap-size overflows and degraded query performance.
Scope
Detection and recommendation
Detection Example
List<Contact> conlist = [SELECT Id,BillingState FROM Contact];
conlist.sort();
Recommendation
Use the ORDER BY clause in SOQL to delegate sorting to the database
layer.
List<sObject> conlist = [SELECT Id, BillingState FROM Contact ORDER BY BillingState];