Efficient way to write apex code
Set.contains(element) Vs List.contains(element)
Guess What if I tell small things Matter!!!
If you’re having a cup of tea, pause for a moment because next two minutes will reveal something simple yet less known it the world of Salesforce
Set && List your favorite go to during the typical development cycle. But going forward you will definitely double check before using them.
For Instance, look at this example
Take two set of collections (Set<Integer> and List<Integer>). Now the crux of the discussion which one will give better performance. Lets get technical
Which will give better performance Set or List ?
a. If collection is List:
List < Integer > listInteger = new List < Integer > ();
for (Integer i = 0; i < 100000; i++) {
listInteger.add(i);
}
Long start = DateTime.now().getTime();
System.debug('get ' + listInteger.contains(100000));
Long finish = DateTime.now().getTime();
System.debug('list time ' + (finish - start));
//This is the computer way of looking at the above Code
for (Integer i: intlist) {
if (i == 100000) {
return true;
}
}
It searches for the element is list. So if the size of list n > 100000. it will iterate through the list 100000 times for worst case i.e for the last element. order of O(n).
b. Now take Set for instance:
Set<Integer> setInteger = new Set<Integer>();
for(Integer i=0;i<100000;i++){
setInteger.add(i);
}
Long start = DateTime.now().getTime();
System.debug('get '+setInteger.contains(100000));
Long finish = DateTime.now().getTime();
System.debug('set time '+(finish-start));
//This is the computer way of looking at the above Code
if hash function is h(ele) = ele % 10;
h(100000) = 100000%10 = 10000;
if(setInt[h(10000)]!=null)
return true;
It takes constant time to return true or false. C1 time to calculate hash value and C2 time to access the value at that index.
C1 + C2 sec = C sec
which is constant time of order O(1).
Given any day which one you would chose for your afternoon coding Saga. #SetLove
Comments
Post a Comment