-1

In apex i trying to take out below for loop inside for loop .

Below Code base is iterating list if Sobject records.

 for(SObject sObj: listRecords){
      Map<String,Vals> RowsValsItemListMap = new Map<String,Vals>();
      List<Vals> ValsItemList = new List<Vals>();
      
      Map<String, Object> fieldsToValue = sObj.getPopulatedFieldsAsMap();
      system.debug('Value for is: fieldsToValue' +fieldsToValue);
      
      map01.put(sObj, fieldsToValue);
      
      for (String fieldName : fieldsToValue.keySet()){
          system.debug('Value for fieldName is: ' +fieldName);                  
          Vals ValsItem = new Vals();                    
          ValsItem.val = fieldsToValue.get(fieldName);                
          //ValsItem.val = (String)fieldsToValue.get(fieldName);                        
          RowsValsItemListMap.put(fieldName.toLowerCase(), ValsItem);                
      }                         
      

}

Any help will be really appriciated.

1 Answers1

1

What is your code trying to achieve? What's the reason you need to eliminate loops, you have some performance issues?

At a glance it looks hard to optimise, you seem to be looping through all rows (sobjects) and all columns (populated fields), it's hard top optimise such thing when making a CSV output for example.

But looking closer I can see some stuff that looks like mistakes. We can optimise them away; the question is whether you really wanted to do these things.

  1. List<Vals> ValsItemList = new List<Vals>(); - this variable seems to not be used anywhere and besides - it's reset on every iteration anyway. Kill it?

  2. Next thing:

    for(SObject sObj: listRecords){
        Map<String,Vals> RowsValsItemListMap = new Map<String,Vals>();
        // ... unimportant
    
        for (String fieldName : fieldsToValue.keySet()){
            // ... unimportant
    
            RowsValsItemListMap.put(fieldName.toLowerCase(), ValsItem);                
        }
    }
    

This RowsValsItemListMap is the outer loop's local variable. There's no point setting it, it'll be invisible outside of the loop anyway. Kill it. If it's needed in some code you didn't paste - look what you're doing. You reset the variable on every iteration. You might have just deleted the outer loop and used inner loop only on the last element (listRecords]listRecords.size()-1]), same result.

  1. That leaves us with pretty much only map01.put(sObj, fieldsToValue);. We don't know what it does and it's probably a mistake to index maps by sObject - if you change a field in the sObject the map's inner hash key will change and you might not be able to find your element anymore. If it's really needed - well, you need only outer loop for this, here's your optimisation.
eyescream
  • 18,088
  • 2
  • 34
  • 46