Here is my code

// dynamic fields, the same with queried fields of Database.query(sqlStr)   
String fieldList = 'Id, Name, Number, Text__c..........'.split(',');
for(SObject sob : Database.query(sqlStr))
    String[] rowValues = new String[] {};
    for(Integer i = 0, j = fieldList.size(); i < j; i++)
        String fieldValueStr = String.valueOf(sob.get(fieldList[i]));
    String joinedRowValues = String.join(rowValues, ' ▏');
    this.values.add(joinedRowValues); // values is from a class property  

the result will be like this

"values": [   
        "00190000014IoCoAAK ▏ 00081 ▏ Super Mart ▏ ...",  
        "00190000014EoCAABK | 0008tator | Test Mart ▏ ...",

If data is more than 5000, there will be lots of loop, for example, we have 30 fields, 5000 records, loop will be 30*5000. Too many loop will cause CPU timeout.
How to reduce this loop and also get the same result?

  • 2
    y can't u directly use JSON.Serialize(sObjectList) ? Mar 4 '16 at 8:20
  • 1
    If you can't change the format, then while you might be able to optimise the code a bit you are always going to be at risk of a limit exception if the maximum number of rows is unknown or grows over time. The general solution to that problem is to use asynchronous Batch Apex.
    – Keith C
    Mar 4 '16 at 9:07

Considering the numbers you provided, I really don't think timing is an issue here. I've wrote the following code to simulate;

String[] l = new String[]{};
for(Integer i=0; i<5000; i++){
    String[] l2 = new String[]{};
    for(Integer j=0; j<30; j++){
    l.add(String.join(l2, '|'));

If I execute this piece anonymously, the Maximum CPU time limit is always below 1000 out of 10000. Of course, depending on the growth of the number of records or fields, or depending on other parts of your code, it could be a problem. But just considering the givens, I don't think it is right now.

  • Such a simple code maybe no problem. But here every field need do a convert, string.valueof(sob.get()). if there are more than 5000 records, let's say 10000, how to reduce the loop? When I run the real code about 10000 records, show this Maximum CPU time: 15108 out of 10000 ******* CLOSE TO LIMIT
    – BruceYue
    Mar 4 '16 at 8:36
  • Ah, I see. In that case it won't work. I get a sense that the output you're giving is to be used in some reporting application or something? Maybe you can just use a Salesforce report?
    – rael_kid
    Mar 4 '16 at 9:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.