In my last post, Apex Tips & Tricks, Bobby Watson commented:
For the two solutions for getting SObject record IDs, it would be interesting to see which one is the most efficient given a list of 1,000 or even 10,000, 50,000 records. Using the map is definitely easier, and I would assume is also the most efficient (but I’ve never done a test on this myself).
To answer Bobby’s question, 1,000 accounts were inserted into a Dev org. Next, apex code was run 5 times through execute anonymous to collect the queried accounts’ ids into a set of ids using three methods:
- For Each Loop. The account ids were collected using a For Each loop.
- For Loop. The account ids were collected using a For Loop using the more traditional for(int i = 0; i < numAccts; ++i).
- Map Constructor. The map has a constructor that takes in a list of SObject and automatically creates a Map<Id, SObject> from it. One can then use map.keySet() to get the set of Ids from it.
The For Each Loop takes the longest followed by the For Loop and finally the Map Constructor. The For Each Loop is roughly 8-9 times slower than using a Map Constructor. The For Loop is roughly 4 times slower than using the Map Contructor.
|Test Run #||For Each Loop||For Loop||Map Constructor|
Apex Profiling Code
The following apex code was run in a Developer org on na9 using Execute Anonymous. The 1,000 accounts were already inserted in the org.
Were the results as you expected? Have you done any other apex profiling?