Difference between trigger.new and trigger.newmap
Suppose you have a custom object Custom_obj__c
Trigger.New
means it is a List<Custom_obj__c>
and
Trigger.NewMap
means it is a map<Id, Custom_obj__c>
In before insert context your Trigger.NewMap
will always be null because in before context records are not submitted to the database, so the Id is not generated yet. That's why in before insert we don't use Trigger.NewMap
But in After insert, Id is generated so we can use Trigger.NewMap
In case of before and after update, the Id has already been generated in the insert event. So we can use Trigger.NewMap
in before and after update.
Let me know if you have any confusion..
trigger.new
is simply a list of the records being processed by the trigger, so if all you need to do is loop through them then you can use that.
trigger.newMap
just allows you to target specific records by Id should you not need to process everything, or if you need to map other records back to these.
Let's take following example.
Suppose you want to get all contact of account object while updating account records and you want to update all contact as well at the same time then you have following option
Loop over the Trigger.New and get all the account ids
set<Id> accIds = new set<Id>(); for(Account acc : Trigger.new) { accIds.add(acc.id); } //query the contact records now from currently processed Account Ids List<Contact> lstContact = [select id from contact where Accountid in : accIds];
Problem with this approach is that if there are 200 account this code will run 200 times because we are using Trigger.new which is list records
Get All the Account ids from Trigger.Newmap
List<Contact> lstContact = [select id from contact where Accountid in : Trigger.newmap.Keyset()];
Above statement will run only 1 time which is always best option to choose from performance perspective.
Conclusion, it all depends what is your requirement. sometime we use Trigger.new and sometime we use Trigger.newMap