Overview
When writing Apex triggers in Salesforce you’ll often work with context variables that provide the records being processed. Two of the most commonly used context variables are Trigger.new and Trigger.newMap. Understanding the differences between them helps you write clearer, safer, and more efficient trigger code.
What is Trigger.new?
Trigger.new is a List
// Example: Iterate and validate fields
for (Account acc : Trigger.new) {
if (acc.AnnualRevenue < 0) {
acc.addError('Annual Revenue cannot be negative');
}
}
What is Trigger.newMap?
Trigger.newMap is a Map that maps record Ids to their new sObject values. It’s useful when you need to quickly look up a record by Id (O(1) lookups) — for example, when comparing old vs new values across related collections or avoiding nested loops.
// Example: Fast lookup by Id
Account changedAcc = Trigger.newMap.get(someAccountId);
if (changedAcc != null) {
// Work with the changedAcc
}
Availability & Context Differences
Knowing which context variables are available in each trigger event is important:
- Trigger.new is available in
before insert,after insert,before update,after update, andafter undelete. It is NOT available indeletetriggers. - Trigger.newMap is available in
before update,after update,after undelete, andafter insert(where Ids are assigned). It is NOT available inbefore insertif the records don’t yet have Ids, and it is NOT available indeletetriggers (useTrigger.old/Trigger.oldMapinstead).
When to use each
Choose based on your need:
- Use
Trigger.newwhen you need to preserve order, transform the entire list, or when working in contexts where Ids are not yet assigned (e.g.,before insertvalidation). - Use
Trigger.newMapwhen you need fast lookup by Id, when comparing toTrigger.oldMapduring updates, or when you want to avoid nested loops to improve performance.
Practical example: update-based comparison
Compare field changes during an update using Trigger.oldMap and Trigger.newMap:
// Trigger on Account (after update)
for (Id accId : Trigger.newMap.keySet()) {
Account newAcc = (Account)Trigger.newMap.get(accId);
Account oldAcc = (Account)Trigger.oldMap.get(accId);
if (newAcc.AnnualRevenue != oldAcc.AnnualRevenue) {
// Revenue changed — take action
}
}
Performance considerations
Maps allow direct lookups which avoids expensive nested loops. When comparing or aggregating across related collections, prefer maps to keep CPU time and heap usage lower.
Quick reference
Trigger.new: List<sObject>, ordered, used for iteration and operations when Ids may not exist.Trigger.newMap: Map<Id, sObject>, fast lookups by Id, best for comparisons and cross-referencing.
Understanding both will make your Apex triggers simpler, more maintainable, and performant.








Leave a Reply