Testing a map key trick
Thu Jul 18 2024 09:33:49 GMT+0000 (Coordinated Universal Time)
Saved by
@Justus
/**
* Method to test Fernando's F' map trick
*/
// Query a 1000 records
Account[] records = [SELECT Id,Name FROM Account WHERE Name LIKE 'Test Account - %' LIMIT 1000];
// Use Fernando's MapCreator Method to
Integer fst = Limits.getCpuTime();
Map<String, SObject> fMap = (Map<String, SObject>) MapCreator.createMapByIndex(records, 'Name' );
Integer fet = Limits.getCpuTime();
System.debug('"Fernanados" method: ' + (fet-fst) + 'ms - Number of records:' + fMap.size());
// Use a traditional for loop
Integer tst = Limits.getCpuTime();
Map<String, SObject> tMap = new Map<String, SObject>();
for(Integer i=0,max=records.size();i<max;i++){
tMap.put(records[i].name,records[i]);
}
Integer tet = Limits.getCpuTime();
System.debug('"Traditional" method: ' + (tet-tst) + 'ms - Number of records:' + tMap.size());
/**
* https://learnsf.wordpress.com/2014/12/29/trick-how-to-obtain-a-map-indexed-by-any-field-not-just-id-faster-and-without-loops/
*/
public class MapCreator {
public static Map<String, SObject> createMapByIndex(List<SObject> aList, String indexField ) {
// get the list in JSON format
String jsonList = JSON.serialize( aList );
// remove enclosing []
jsonList = jsonList.substring( 1, jsonList.length() - 1 );
// copy the indexField value in front of each
// {} group using RegEx substitution
// example result: value:{…"indexField":"value"…}
jsonList = '{' + jsonList.replaceAll('(\\{.*?"' + indexField + '":"(.*?)"(,".*?")*\\},?)', '"$2":$1' ) + '}';
// create map from the modified JSON
Map<String, SObject> changedMap = (Map<String, SObject>) JSON.deserialize( jsonList, Map<String, SObject>.class );
return changedMap;
}
}
content_copyCOPY
Comments