Apex Profiling: Collecting Set From List

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:

  1. For Each Loop. The account ids were collected using a For Each loop.
  2. For Loop. The account ids were collected using a For Loop using the more traditional for(int i = 0; i < numAccts; ++i).
  3. 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.

Profile Results

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
1 77ms 34ms 9ms
2 64ms 28ms 7ms
3 78ms 31ms 9ms
4 78ms 30ms 43ms
5 95ms 30ms 9ms

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?

One thought on “Apex Profiling: Collecting Set From List

  1. Interesting post Luke!

    One question I had on the results were what were the debug settings? I’m curious how the timings are with all debugging off except for System level set to Debug since logging is synchronous and would be included in the timings.

Leave a Reply

Your email address will not be published. Required fields are marked *