0

I am new to coding.here i want to replace the two for loop using map.can we do it?

ContentVersion versionIn = [
    SELECT VersionData, VersionNumber, PathOnClient
    FROM ContentVersion
    WHERE ContentDocumentId = :contentDocumentId
    AND IsLatest = TRUE
    LIMIT 1
];

String fileContentIn = versionIn.VersionData.toString();
List<List<String>> rowsIn = CsvReader.read(fileContentIn);
for (Integer row = 1; row < rowsIn.size(); row++) {
    List<String> columns = rowsIn[row];
    for(integer col = 1; col<coulumns.size();col++){
        
    }
}    
2
  • 3
    Best you explain what logic you are aiming to implement; using maps may not be relevant to that.
    – Keith C
    Commented Jan 6, 2022 at 9:11
  • i need to get the uploaded csv file cell address if there are any issue in the cell.so the mention code i am using to loop row value and the column.then it show like heap limitation.Therefore i need to use map for that
    – Basu
    Commented Jan 6, 2022 at 9:59

1 Answer 1

2

Converting an inner loop to a map makes no sense if you're trying to deal with every cell in every row in a CSV, and other such scenarios. I've talked about nested loops before; there are times when they are necessary, such as here. Replacing a nested loop with a map will not improve performance in this case. Also, replacing nested loops with maps will rarely ever solve heap limit exceptions; maps are best used to solve CPU timeouts from excessive unnecessary processing.

In order to free up heap space to avoid heap limit exceptions, you need to free memory as early as possible. You can do this by avoiding temporary variables:

List<List<String>> rowsIn = CsvReader.read([
    SELECT VersionData, VersionNumber, PathOnClient
    FROM ContentVersion
    WHERE ContentDocumentId = :contentDocumentId
    AND IsLatest = TRUE
    LIMIT 1
].VersionData.toString());

This avoids leaving a copy of the string in memory as both a string and blob, reducing memory usage by up to 50%. Of course, it also depends on how your CsvReader is written. Most CSV Readers assume unlimited memory, but if your csv reader is "destructive" (i.e. it actually removes parsed content from the source string as it parses), you can get the actual memory usage down significantly.

4
  • Thank You i will work on it and update
    – Basu
    Commented Jan 6, 2022 at 17:33
  • can you please tell me if i need any case to use map what will be the way i do use map like this kind of iteration
    – Basu
    Commented Jan 6, 2022 at 17:41
  • @Basu look at my linked answer for a situation where you'd use a map.
    – sfdcfox
    Commented Jan 6, 2022 at 17:45
  • Thank you for the information
    – Basu
    Commented Jan 6, 2022 at 17:57

Not the answer you're looking for? Browse other questions tagged .