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
niraj kumar 45niraj kumar 45 

Error In apex class : Apex CPU time limit

Hi I am getiing below error 
System.LimitException: Apex CPU time limit exceeded
Below is my code:
                            for(content_description__c cds: contentDesc){
                                        brandNameStringSet = new set<string>();
                                        for(ContentBrand__c cntBrnd : contentBrandMap.values()){
                                            if(cntBrnd.Content_Description__c!=NULL){ 
                                                if(cds.Id == contentBrandMap.get(cntBrnd.Id).Content_Description__c){
                                                    brandNameStringSet.add(cntBrnd.Brand__r.Name);
                                                }
                                            }
                                        }
                                       mapBrand.put(cds.id,brandNameStringSet);
                                 }
I am getting error at the line which is highlighted in bold in the above code.
I am gettin size for ist for loop is 787 and for the seconf for loop size is 848.
I tried reversing the for loop but still no luck.
I need this both for loop. I cannot remove the for loop.
How do I solve this isue?
AvaneeshAvaneesh
Hi Niraj

Can you please paste your complete code and this error generally comes when code complexity is too high. so if you share your code then I will help you for reducing the complexity of the program. well using nested for is not a good programming so it is better to use Map collection 

https://help.salesforce.com/articleView?id=000232681&language=en_US&r=https:%2F%2Fwww.google.co.in%2F&type=1

Thank you
Avaneesh Singh
niraj kumar 45niraj kumar 45
Hi Avaneesh,

Thank you for you quick response.
Below is my complete method:
 public void sliderSearchRecords(){ 
       try{
            if(searchstring!=NULL && searchstring.trim()!=''){
                    string brandIdString;   
                    system.debug('==in mthd==');
                    sliderRangeVal = ApexPages.currentPage().getParameters().get('rangeVal');
                    system.debug('==value is=='+sliderRangeVal);
                        showSixMnthsRcrdsPanel = true;
                    Set < ID > brandIdsSet = new Set < Id > ();
                    List < ID > userBrands = new List < ID > (Service_API.getAccBrandIdsIndpntTheme());
                    brandIdsSet = Service_API.getContentBrandIDsIndpntTheme(userBrands);
                    System.debug('==brandIdsSet  size=='+brandIdsSet.size()); 
                    if(sliderRangeVal == '6'){
                        accts = new Map<Id,ContentDocument>([Select Id, IsArchived from ContentDocument where ID IN :brandIdsSet And IsArchived = False AND createdDate = LAST_N_DAYS:180]);
                    }else if(sliderRangeVal == '12'){
                        accts = new Map<Id,ContentDocument>([Select Id, IsArchived from ContentDocument where ID IN :brandIdsSet And IsArchived = False AND createdDate = LAST_N_DAYS:366]);
                    
                    
                    }else if(sliderRangeVal == 'All'){
                        accts = new Map<Id,ContentDocument>([Select Id, IsArchived from ContentDocument where ID IN :brandIdsSet And IsArchived = False]);
                    }else if(sliderRangeVal == '3'){
                        accts = new Map<Id,ContentDocument>([Select Id, IsArchived from ContentDocument where ID IN :brandIdsSet And IsArchived = False AND createdDate = LAST_90_DAYS]);
                    }
                    //original query
                    //accts = new Map<Id,ContentDocument>([Select Id, IsArchived from ContentDocument where ID IN :brandIdsSet And IsArchived = False]);
                    Set<Id> IdSet = accts.keySet();  
                    System.debug('==IdSet size=='+IdSet.size());
                    if (!IdSet.isEmpty()) {
                       brandIdString = IdSetToString(IdSet);
                    }
                    
                            
                            // query with portfolio= true removed
                            //String queryString = 'SELECT Name,Tags__c,is_video__c,Content_Id__c,video_id__c,Title__c,Description__c,Content_Version_Id__c,filetype__c,Preview_Available__c,Preview_Id__c,filesize__c,filesize_low__c,Content_Version_Id_Low__c,createdDate,image_resolution__c,share_link__c, share_link_low__c FROM content_description__c ' + ' WHERE (Content_Id__c in (' + brandIdString + ')) ' + ' AND ((Title__c like \'%' + searchValue + '%\' OR Description__c like \'%' + searchValue + '%\' OR Tags__c like \'%' + searchValue + '%\'))'; 
                            //original query 
                            String queryString = 'SELECT Name,Tags__c,is_video__c,Content_Id__c,video_id__c,Title__c,Description__c,Content_Version_Id__c,filetype__c,Preview_Available__c,Preview_Id__c,filesize__c,filesize_low__c,Content_Version_Id_Low__c,createdDate,image_resolution__c,share_link__c, share_link_low__c FROM content_description__c ' + ' WHERE (Content_Id__c in (' + brandIdString + ') OR ( Portfolio__c = true ) ) ' + ' AND ((Title__c like \'%' + searchValue + '%\' OR Description__c like \'%' + searchValue + '%\' OR Tags__c like \'%' + searchValue + '%\'))'; 
                            
                            //modified query with removing like %
                              //String queryString = 'SELECT Name,Tags__c,is_video__c,video_id__c,Title__c,Description__c,Content_Version_Id__c,filetype__c,Preview_Available__c,Preview_Id__c,filesize__c,filesize_low__c,Content_Version_Id_Low__c,createdDate,image_resolution__c,share_link__c, share_link_low__c FROM content_description__c ' + ' WHERE (Content_Id__c in (' + brandIdString + ') OR ( Portfolio__c = true ) ) ' + ' AND ((Title__c like \'' + searchValue + '%\' OR Description__c like \'' + searchValue + '%\' OR Tags__c like \'' + searchValue + '%\'))';   
                               System.debug('---queryString - '+queryString);
                               
                               contentDesc = database.query(queryString + 'ORDER BY createdDate desc limit 1000');
                                
                                
                                System.debug('---contentDesc - '+contentDesc +'==size=='+contentDesc.size());
                                contDesId = new Set<Id>();
                                for(content_description__c cds : contentDesc){
                                    contDesId.add(cds.Id);
                                    //System.debug('---contentDesc Id - '+cds.Content_Id__c );
                                }
                                
                               
                                Map<id,ContentBrand__c> contentBrandMap= new Map<id,ContentBrand__c>([Select Id,Content_Description__c,Brand__c,Brand__r.Name from ContentBrand__c where Content_Description__c IN :contDesId limit 50000]);
                                
                                
                                Map<id,ContentBrand__c> mapCntBrand = new Map<id,ContentBrand__c>();
                                Map<id,set<string>> mapBrandName = new Map<id,set<string>>();
                                
                                Map<id,List<ContentBrand__c>> mapDescCntBrand = new Map<id,List<ContentBrand__c>>();
                                set<string> brandNameStringSet;
                                mapBrand = new map<id,set<string>>();
                               // system.debug('==size is=='+contentBrandMap.values().size());
                                
                                    for(content_description__c cds: contentDesc){
                                        brandNameStringSet = new set<string>();
                                        for(ContentBrand__c cntBrnd : contentBrandMap.values()){
                                            if(cntBrnd.Content_Description__c!=NULL){ 
                                                if(cds.Id == contentBrandMap.get(cntBrnd.Id).Content_Description__c){
                                                    brandNameStringSet.add(cntBrnd.Brand__r.Name);
                                                }
                                            }
                                        }
                                       mapBrand.put(cds.id,brandNameStringSet);
                                    }
                                    
                                   
                               
                                //code for content property starts here
                                List<Content_Property__c> cntentProprty = new List<Content_Property__c>();
                                if(!contentDesc.isEmpty() && contentDesc!=NULL){
                                    //without product images and logos
                                    cntentProprty = [select id,Name,Category__c,Sub_Category__c,Start_Date__c,End_Date__c,Content_Description__c from Content_Property__c where Content_Description__c IN:contDesId AND Category__c != 'Product Images & Logos'];
                                    //with product images and logos
                                    //cntentProprty = [select id,Name,Category__c,Start_Date__c,End_Date__c,Content_Description__c from Content_Property__c where Content_Description__c IN:contDesId];
                                    system.debug('content property is'+cntentProprty +'size is::'+cntentProprty.size());
                                }
                                Map<Id,Content_Property__c> mapContentPrprty;
                                if(cntentProprty!=NULL && !cntentProprty.isEmpty()){
                                   mapContentPrprty = new Map<Id,Content_Property__c>();
                                   for(Content_Property__c cts:cntentProprty){
                                       mapContentPrprty.put(cts.Content_Description__c,cts);
                                       
                                   }
                                }
                                
                                }
                               
            }//end of null search string check if
         } catch (QueryException e){
          
        }
       
   }
AvaneeshAvaneesh
Hi Niraj,
I get your Solution for Reducing its complexity 

 
// line no 53 

Map<id,ContentBrand__c> contentBrandMap= new Map<id,ContentBrand__c>([Select Id,Content_Description__c,Brand__c,Brand__r.Name from ContentBrand__c where Content_Description__c IN :contDesId limit 50000]);

//Make this Map as a following way and Content_Description__c is a key 
Map<String ,ContentBrand__c> contentBrandMap = new Map<String,ContentBrand__c>();

// here i am puting Content_Description__c  as a key and ContentBrand__c  as a value

for(ContentBrand__c cb: [Select Id,Content_Description__c,Brand__c,Brand__r.Name from ContentBrand__c where Content_Description__c IN :contDesId limit 50000]) {
 contentBrandMap.put(cb.Content_Description__c , cb);
}

and now you have to change your logic with something like this way 
/*
 for(content_description__c cds: contentDesc){
                                        brandNameStringSet = new set<string>();
                                        for(ContentBrand__c cntBrnd : contentBrandMap.values()){
                                            if(cntBrnd.Content_Description__c!=NULL){ 
                                                if(cds.Id == contentBrandMap.get(cntBrnd.Id).Content_Description__c){
                                                    brandNameStringSet.add(cntBrnd.Brand__r.Name);
                                                }
                                            }
                                        }
                                       mapBrand.put(cds.id,brandNameStringSet);
                                    }

*/

// Remove both for loop and start with my logic


/*********************************************************************************************************/
 
for(content_description__c cds: contentDesc){
   if(contentBrandMap.containsKey(cds.id)){ // this line i am finding with your code logic it will work fine
   brandNameStringSet = new set<string>();
   brandNameStringSet.add(contentBrandMap.get(cds.id).Brand__r.Name);
   mapBrand.put(cds.id,brandNameStringSet);
 }
}
in just above code if condition I find with your code logic it will work 
if there is any syntax mistake please resolved it your self 

please don't forget to mark as best answer else let me know your problem 

Thank you 
Avaneesh Singh

 
niraj kumar 45niraj kumar 45
Hi Avaneesh,

Thanks for your response. I have already tried the way way you have suggested when i was writing the code. But here Content Brand is a junction object of Brand Object and Content Description object. So Content Description Object can have multiple brands. So I need all the brands names for their respective Content description. So brandNameStringSet.add(contentBrandMap.get(cds.id).Brand__r.Name); logic I cannot use as it will return single brand name as map is intialise with Map<String ,ContentBrand__c> contentBrandMap = new Map<String,ContentBrand__c>(); . So in map I need a map with Content Description Id and list of Brands name. So thats why I was iterating on in two For loops. So please let me know how can I optimize the code to get Content Description Id and list of Brands Name for that Content Description Id.
AvaneeshAvaneesh
Hi 

Try this and  go for the List of contentBrand__c 
Map<String ,List<ContentBrand__c>> contentBrandMap = new Map<String,List<ContentBrand__c>>();

Thank you
Avaneesh Singh
 
niraj kumar 45niraj kumar 45
Foe making Map<String ,List<ContentBrand__c>> contentBrandMap = new Map<String,List<ContentBrand__c>>(); .I have to iterate over  ContentBrand__c and Content Description. Again then I will get the same issue that I am facing now.