From a performance view point which is better:

Set<String> uniqueStrings = new Set<String>();

// Keep checking for null and then add to Set
for (Integer i = 0; i < 100; i++) {
    if(somevalue !== null){

// Add everything to Set and then remove null at the end
for (Integer i = 0; i < 100; i++) {

In my view as we have an conditional statement inside for loop, that should increase time-complexity. But the later should not. Any thoughts?

1 Answer 1


Your gut feeling is somewhat correct. It's hard to get precise measurements because of the nature of how Apex executes on a shared resource, but generally speaking, if you anticipate less than about 50 values, using the if statement is very, very slimly faster (~1/100th of a second), and for about every ~200 values, the if statement version takes longer than the remove-null-at-end by another millisecond or so.

The if statement has a small advantage with a low amount of data, because hash codes take time to compute, but this is later dwarfed by the sheer number of if statements evaluated. Thus, from a performance optimization point of view, the answer is essentially "it doesn't matter which you use."

However, two important points to note, and this is why I always use the remove-null-at-end approach: cyclomatic complexity is reduced by 1, and the code is very slightly shorter, making it more legible. Using this pattern consistently would slightly reduce cognitive load, and make Apex PMD a little bit happier about one less branching statement.

If you're seriously hurting on CPU time, and you're looking for a quick fix, switching to remove-null-at-end won't help you; you'd need to be able to use it 20 times to even make a 1 second difference in CPU time, assuming 10,000 items in each pass, which is likely already going to blow up the CPU limits.

  • Thanks for detailed insights. Yes, looks like we cannot test the exact performance, but only depend on theory here. Apr 9, 2021 at 7:50
  • 1
    @NagendraSingh I did do some testing, averaged some numbers together, it's more of a working theory than a hypothetical theory.
    – sfdcfox
    Apr 9, 2021 at 9:04
  • Ok, thanks that's helpful. Apr 9, 2021 at 9:09

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .