Home >Web Front-end >JS Tutorial >Why is my Google Apps Script so slow, and how can I optimize `getValues` and `setValues` usage?
Long Processing Time Due to Excessive Use of getValues and setValues
Issue:
The code suffers from excessive usage of the getValues and setValues methods, which can significantly impact processing time, especially for larger data sets.
Optimization Techniques:
Minimize Service Calls:
Look-Ahead Caching:
Minimize Read/Write Operations:
Avoid Alternating Read/Writes:
Use Arrays:
Example:
Consider the following code snippet:
// Slow version: Alternating read and write operations const sourceRange = SpreadsheetApp.getActiveSheet().getRange("A1:D2"); const targetRange = sourceRange.offset(2, 0); for (let i = 0; i < sourceRange.getNumRows(); i++) { for (let j = 0; j < sourceRange.getNumColumns(); j++) { const value = sourceRange.getCell(i + 1, j + 1).getValue(); targetRange.getCell(i + 1, j + 1).setValue(value); } } // Fast version: Batch read and write operations const sourceValues = sourceRange.getValues(); targetRange.setValues(sourceValues);
By batching read and write operations, the second code snippet significantly reduces the number of calls to services and improves processing time.
The above is the detailed content of Why is my Google Apps Script so slow, and how can I optimize `getValues` and `setValues` usage?. For more information, please follow other related articles on the PHP Chinese website!