function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion

Map and Set Pattern/Performance Question

I am trying to understand the best patter/performance way to build a map or set.  So for example, if I am building a set of say 40,000 rows that may have duplicates coming in (I know the set would over write the current position) is that faster than if I check if the value exists first with an IF statement ( i.e.: if ( !myset.contains(valueAdding)) {myset.add(valueAdding);} )?  My question is for Maps as well.

I typically have been simply adding the value and not checking because I thought if I had a large number (several thousand that the CONTAINS method check would slow the process down; however, on the other had in the background does it take a lot more processor time to add a value?  I don't know -- looking for some feedback please! :)

PratikPratik (Salesforce Developers) 

While adding your rows to set, you can skip the duplicate check as Set will take care of duplicates. 
When you are adding the rows to the map, Map will have key & value pair in which key will be unique so there aslo you really don't need check for duplicates.

If you want to have check for duplicate in either set or map, you can go for it as will not slow down too that extent. You can try the approach and see how much time it takes through logs.

I think the check might take lesser time, and increase performance, as "put" on map would try to locate the variable and then over-write, unconditionally... logically it seems write operation would take more time than just checking. You should try and see though.