Very slow execution of for…in loop

前端 未结 2 1053
猫巷女王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:33

    I was not sure about //do something after complete. So how about these 2 patterns. Please think of this answer as one of several answers.

    I modified your script to replace setValue() to setValues(). By this, the process speed will be fast.

    Pattern 1 :

    function getData1() {
      var sh = SpreadsheetApp.getActiveSheet();
      var response = UrlFetchApp.fetch(endpoint);
      var data = JSON.parse(response);
      var rates = data["quotes"];
    
      var keys = Object.keys(rates);
      var dat = [];
      keys.forEach(function(key){
        if (key != keys[keys.length - 1]) {
          dat.push([key.substring(3), rates[key]]);
        } else {
          //do something after complete
        }
      });
      sh.getRange(2, 1, dat.length, dat[0].length).setValues(dat);
    }
    

    Pattern 2 :

    function getData2() {
      var sh = SpreadsheetApp.getActiveSheet();
      var response = UrlFetchApp.fetch(endpoint);
      var data = JSON.parse(response);
      var rates = data["quotes"];
    
      var dat = Object.keys(rates).map(function(key){return [key.substring(3), rates[key]]});
      sh.getRange(2, 1, dat.length, dat[0].length).setValues(dat);
    
      //do something after complete
    }
    

    Note :

    • If this didn't work, can you provide a sample data from var response = UrlFetchApp.fetch(endpoint);? Of course, please remove the private information from it.

    Refecences :

    • setValue(value)
    • setValues(values)
    • Best Practices

    If I misunderstand your question, I'm sorry.

提交回复
热议问题