Very slow execution of for…in loop

前端 未结 2 1052
猫巷女王i
猫巷女王i 2020-12-21 14:13

I am populating a spreadhsheet from data I am getting from an external endpoint. Everything is working, but the execution of the for...in loop is incredibly slow.

Th

2条回答
  •  一整个雨季
    2020-12-21 14:40

    The problem is not with the size of your object. You are repeatedly calling sheet.getRange() to get every individual cell in the target range which is redundant. Keep read/process/write operations completely separate from each other to optimize performance. 1) Retrieve values 2) Process them, and 3) Call 'setValues()' on the target range. This took less than 0.2 seconds to finish:

     var arr = [];
    
      for (var [prop, val] in hugeObject) {
    
        arr.push([prop, val]);  
    
      }
    
      var targetRange = SpreadsheetApp.getActive()
                                      .getSheets()[0]
                                      .getRange(2, 1, arr.length, arr[0].length)
                                      .setValues(arr);
    

提交回复
热议问题