How to Improve Script to Reduce Process Cost

I am setting value in col4 based on if I have actualized dates in col2 and col3. I have to run this code on a large dataset, and takes too long. How can I reduce the process cost and make it execute fast?

My code is below:

function myFunction() {
  
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
  var row = 2;

  for(row; row<=sheet.getLastRow(); row++ ){
    if(sheet.getRange(row,2).getValue()!="" && sheet.getRange(row,3).getValue()!=""){
      sheet.getRange(row,4).setValue("Advance paid and materials ordered");
    }
    else if(sheet.getRange(row,2).getValue()=="" && sheet.getRange(row,3).getValue()!=""){
      sheet.getRange(row,4).setValue("Materials ordered");
    }
    else if(sheet.getRange(row,2).getValue()!="" && sheet.getRange(row,3).getValue()==""){
      sheet.getRange(row,4).setValue("Advance paid");
    }
  }
}

Before:

Spreadsheet-Before

Output:

Spreadsheet-Before


I believe your goal is as follows.

  • You want to reduce the process cost of your script.

In this case, how about the following modification?

Modified script:

function myFunction() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
  var row = 2;
  var values = sheet.getRange(row, 2, sheet.getLastRow() - (row - 1), 2).getValues();
  var res = values.map(([b, c]) => [b != "" && c != "" ? "Advance paid and materials ordered" : b == "" && c != "" ? "Materials ordered" : b != "" && c == "" ? "Advance paid" : ""]);
  sheet.getRange(row, 4, res.length, 1).setValues(res);
}
  • In this modification, the values are retrieved from the columns "B" and "C", and create an array for putting to the sheet, and then, the array is put to the column "D".

Reference:

  • map()