Caching & Performance Enhancements in Apex
What Is Performance Optimization in Apex?
Short Description
Performance optimization means doing less work to get the same result—faster response, lower limits usage, and better user experience.
Simple Explanation
Instead of cooking the same meal every time, store it and reheat.
Gist (Quick Revision)
Optimized Apex reduces CPU time, memory usage, and repeated database calls.
1. Platform Cache
What Is Platform Cache?
Platform Cache stores frequently used data in memory, so Salesforce doesn’t need to query the database repeatedly.
Simple Explanation
Platform Cache is like a fridge—keep frequently used items ready instead of cooking again.
When to Use Platform Cache
-
Reusable reference data
-
Configuration values
-
Frequently accessed records
Platform Cache Example
Cache.OrgPartition partition = Cache.Org.getPartition('MyCache');
String cachedValue = (String) partition.get('discountRate');
if (cachedValue == null) {
cachedValue = '10%';
partition.put('discountRate', cachedValue);
}
Benefits
-
Faster performance
-
Fewer SOQL queries
-
Lower CPU usage
Gist (Quick Revision)
Platform Cache speeds up Apex by storing reusable data in memory.
2. Query & Logic Optimization
Why Query Optimization Matters
Salesforce enforces strict SOQL and CPU limits. Poor queries slow everything down.
Best Practices for SOQL Optimization
1. Query Only What You Need
❌ Bad
SELECT * FROM Account
✅ Good
SELECT Id, Name FROM Account
2. Use WHERE Filters
WHERE CreatedDate = LAST_N_DAYS:30
3. Avoid SOQL in Loops
// Use collections and maps instead
Logic Optimization Tips
-
Move heavy logic outside loops
-
Use
breakandcontinuewisely -
Reuse results instead of recalculating
Real-Life Example
Instead of checking eligibility repeatedly, check once and reuse the result.
Gist (Quick Revision)
Efficient queries and clean logic dramatically reduce governor limit usage.
3. Memory Efficiency (Heap Management)
What Is Heap Memory?
Heap memory stores Apex variables and objects during execution.
Simple Explanation
Heap is your workspace desk—too many items cause clutter.
Common Memory Mistakes
-
Storing large objects unnecessarily
-
Keeping data longer than needed
-
Loading entire records when few fields are needed
Memory-Efficient Example
List<Account> accounts = [SELECT Id, Name FROM Account]; accounts.clear(); // free memory when no longer needed
Best Practices for Memory Efficiency
-
Query minimal fields
-
Clear large collections after use
-
Use pagination for large data sets
-
Process records in batches
Gist (Quick Revision)
Good memory management prevents heap size errors and improves performance.
✅ Final Takeaway
Performance tuning is not optional—it’s mandatory in Salesforce’s multi-tenant world.
Fast, efficient Apex = scalable Salesforce solutions
