As we know, a Set is a collection of unique elements (cannot contain duplicates)
While writing some Apex just now, I was inclined to use !SetName.contains(Id)
to skip the addition of records if they were already in the Set. As I was writing it, I realized that I was being redundant, since a Set can't contain more than one instance of the same Id anyway.
However, I was curious about the performance implications of one option versus the other in a bulk sense, thinking that one approach may save on CPU time over the other.
My assumption was based on thinking that Set.add()
uses the Set.contains()
method itself to check if the Record is already in the Set to avoid duplicates, so by using Set.contains()
myself inside my loop, I would take up less CPU time by avoiding passing duplicates into Set.add()
just so that Set.add()
could run Set.contains()
However, using the following 2 Execute Anonymous Tests, the CPU time was nearly identical in all tests (within 1-2 milliseconds).
So the question is: is there a performance difference between checking for an item in a Set manually before adding it, versus letting the Set figure it out on its own? Is my test just too rudimentary or small to see an obvious difference in performance, or should I not be concerned with which style I choose?
Example 1:
Integer limitStart = System.Limits.getCpuTime();
List<Id> stringList = new List<String>();
Set<String> testStrings = new Set<String>();
for(Integer i = 0;i<200;i++){
stringList.add('TestString');
}
for(String s : stringList){
if(!testStrings.contains(s))
testStrings.add(s);
}
Integer limitEnd = System.Limits.getCpuTime();
System.debug('Strings: ' + testStrings);
System.debug('Start: ' + limitStart);
System.debug('End: ' + limitEnd);
Example 2:
Integer limitStart = System.Limits.getCpuTime();
List<Id> stringList = new List<String>();
Set<String> testStrings = new Set<String>();
for(Integer i = 0;i<200;i++){
stringList.add('TestString');
}
for(String s : stringList){
testStrings.add(s);
}
Integer limitEnd = System.Limits.getCpuTime();
System.debug('Strings: ' + testStrings);
System.debug('Start: ' + limitStart);
System.debug('End: ' + limitEnd);