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
Pubali Banerjee 2Pubali Banerjee 2 

getting apex cpu limit exceed error even after keeping in mind the apex considerations

I have the below code. Getting Apec CPU time limit exceeded error while excecution. Checked log and found that the error is happening while assigning the values in for look ( I have marked it as bold). What can i do to optimize this code block further?

Code:
@AuraEnabled(cacheable=true)   
public static List<tsfwrapper> TSFQuery(String sortBy, String sortDirection, String searchKey)
{
/* get the current user's id */
Id user_Id= UserInfo.getUserId();
set<Id> accIds = new set<Id>();
Set <Id> userTerritoryId = new set <Id>();
Set <String> userTerritoryName = new Set <String>();
List<tsfwrapper> twrp = new List<tsfwrapper> ();
List<Account> accList = new List<Account>();


/* get the territories assigned to the user */   
String terrName='';
List<UserTerritory2Association> utList = [SELECT Id,Territory2.Name,Territory2Id,UserId,User.Primary_Territory_vod__c FROM UserTerritory2Association WHERE UserId=:user_Id];
integer i=0;
     if(utList.size()>0){
    for(UserTerritory2Association utForLoop:utList){
        string primaryTerr = utForLoop.User.Primary_Territory_vod__c;
        system.debug('@@ checking if Primary Territory is present or not'+primaryTerr);
       if(i<1){
           if(primaryTerr!=null){
               system.debug('@@ I am here under Primary territory');
               terrName= primaryTerr;  
           }else{
               system.debug('@@ I am here where NO Primary territory is present');
               terrName= utForLoop.Territory2.Name;
           }
       }
        else{
            break;
        }
        i++;
        } 
     }
    system.debug('@@ Territory Name:'+terrName);
/* get all the accounts belonging to the user territory */  
List<ObjectTerritory2Association> otaList =[SELECT Id,ObjectId,SobjectType,Territory2Id FROM ObjectTerritory2Association where Territory.Name=:terrName and Object.Recordtype.DeveloperName='MSD_CORE_Professional' limit 10000];
for(ObjectTerritory2Association objterr:otaList )
{
accIds.add(objterr.ObjectId);
}
Map<Id, TSF_vod__c> tsfMap = new Map<id,TSF_vod__c>();
List<TSF_vod__c> tsfList = [select id,Account_vod__c,MSD_CORE_My_Last_Used_Address__c,MSD_CORE_My_Last_Used_Location__c,Last_Activity_Date_vod__c,YTD_Activity_vod__c,MSD_Alignment_Request__c,Account_vod__r.Name,My_target_vod__c,Territory_vod__c from TSF_vod__c where Account_vod__c =:accIds and territory_vod__c =:terrName and Account_vod__r.MSD_CORE_Account_Status__c='Active'];
for(TSF_vod__c tsfMapRec:tsfList ){
    if(tsfMapRec!=null){
        tsfMap.put(tsfMapRec.Account_vod__c,tsfMapRec);
     }
}

    String query = 'select id,Name from Account where id=:accIds and MSD_CORE_Account_Status__c=\'Active\'';
    if ( searchKey != null && searchKey != '' ) {
           String key = '%' + searchKey + '%';
           query += ' and Name LIKE :key';
       }
    if ( sortBy != null && sortDirection != null ) {
           query += ' ORDER BY ' + sortBy + ' ' + sortDirection;
       }
    accList = Database.query(query);
/* Below code block gives the CPU Limit error */    
    for(Account acc: accList)
    {
        Id accIdVar = acc.Id;
        system.debug('*****Account ID'+accIdVar);
        tsfwrapper newWrap = new tsfwrapper();
        if(tsfMap.Keyset().contains(accIdVar)){
        if(tsfMap.get(accIdVar)!=null){
           newWrap= new tsfwrapper(tsfMap.get(accIdVar).Id,tsfMap.get(accIdVar).Account_vod__r.Name,tsfMap.get(accIdVar).Account_vod__c,tsfMap.get(accIdVar).Territory_vod__c,tsfMap.get(accIdVar).YTD_Activity_vod__c,tsfMap.get(accIdVar).Last_Activity_Date_vod__c,tsfMap.get(accIdVar).MSD_Alignment_Request__c,tsfMap.get(accIdVar).My_Target_vod__c,tsfMap.get(accIdVar).MSD_CORE_My_Last_Used_Address__c,tsfMap.get(accIdVar).MSD_CORE_My_Last_Used_Location__c );
  }
        }
        else
        {
            system.debug('******Inside Null List');
            newWrap= new tsfwrapper(null,acc.Name,acc.Id,terrName,0.0,null,false,false,'','' );
}
        
        twrp.add(newWrap);  
    }
    twrp.sort(); 
    return twrp;         
}
Please help me, I have read the articles but i am at loss.
Note: This apex is the controller for LWC.