Home >Web Front-end >JS Tutorial >How Can I Optimize Google Apps Script to Reduce Excessive Processing Time Caused by Frequent Range.getValue() and Range.setValue() Calls?
The script scans a column of customer order information, identifying state codes and combining first and last names. It also inserts blank rows where necessary. However, processing time becomes excessive for large columns due to frequent calls to Range.getValue() and Range.setValue().
To reduce processing time, it is recommended to minimize calls to Google's services, including Range.getValue() and Range.setValue(). The following optimizations can be implemented:
Below is an optimized script that addresses the excessive processing time issue:
function format() { const SS = SpreadsheetApp.getActiveSpreadsheet(); const SHEET = SS.getActiveSheet(); const LAST_ROW = SHEET.getRange('A:A').getLastRow(); let row, range1, cellValue, offset1, offset2, offset3; // Loop through all cells in column A for (row = 0; row < LAST_ROW; row++) { range1 = SHEET.getRange(row + 1, 1); // If cell substring is a number, skip it as substring cannot process numbers cellValue = range1.getValue(); if (typeof cellValue === 'number') continue; // Check for the state code prefix "-" const DASH = cellValue.substring(0, 1); // Get neighboring cells offset1 = range1.offset(1, 0).getValue(); offset2 = range1.offset(2, 0).getValue(); offset3 = range1.offset(3, 0).getValue(); // Handle state code "-" if (DASH === '-') { // Merge cells 1 and 2 and write "Order complete" in cell 2 range1.offset(1, 0).setValue(offset1 + ' ' + offset2); range1.offset(2, 0).setValue('Order complete'); } // Insert cell if offset 3 is not blank if (DASH === '-' && offset3 !== '') { // Select cells from 3 rows down SHEET.getRange(row + 1, 1, LAST_ROW) .offset(3, 0) .moveTo(range1.offset(4, 0)); } } }
By following these optimizations, the script will significantly reduce processing time by minimizing expensive calls to Range.getValue() and Range.setValue().
The above is the detailed content of How Can I Optimize Google Apps Script to Reduce Excessive Processing Time Caused by Frequent Range.getValue() and Range.setValue() Calls?. For more information, please follow other related articles on the PHP Chinese website!