I am calling the following appscript function using google.script.run from my mobile application.
Code
function addOrUpdateEntry(response) {
let sheetName = "X";
var lock = LockService.getDocumentLock(); //Use Document Lock as we can also be editting these fields.
var lockTimeoutMS = 5000; // 5,000 ms = 5 seconds
var ss = SpreadsheetApp.openById(getSpreadsheetId())
var sheet = ss.getSheetByName(sheetName);
var data = JSON.parse(response);
var a= data.a;
var b= data.b;
var c= data.c;
var d= data.d;
var f= data.f;
var username = data.username;
var todayDateDDMMYYYY = GetCurrentDateAsDDMMYYYY();
var g= data.g;
if (g< 0) {
g= g* -1; //Make it positive.
}
if (lock) {
var success = lock.tryLock(lockTimeoutMS);
if (!success) {
throw new Error("Unable to attain lock.");
}
}
var dataRange;
var values;
try {
dataRange = sheet.getDataRange();
values = dataRange.getValues();
var result = []
/**
* find list of rows to update
*/
for (let i = 1; i < values.length; i++) {
if (
(values[i][TableToColumnLookup[sheetName]["a"]] == a) &&
(values[i][TableToColumnLookup[sheetName]["b"]] == b) &&
(values[i][TableToColumnLookup[sheetName]["c"]] == c) &&
(values[i][TableToColumnLookup[sheetName]["d"]] == d)) {
result.push(i);
}
}
let newData = [a, b, c, d, e, g, username, todayDateDDMMYYYY];
if (result.length > 0) {
/**
* update rows with new data
*/
for (let j = 0; j < result.length; j++) {
sheet.getRange(result[j] + 1, 1, 1, newData.length).setValues([newData]);
}
} else {
/**
* update rows with new data
*/
sheet.appendRow(newData);
}
return JSON.stringify(true);
}
catch (err) {
throw err;
}
finally {
if (lock) {
lock.releaseLock();
}
}
}
The function takes 2-3 seconds to execute for a sheet with 1000 rows. In the client app, it takes 5-6 seconds to receive the REST API result using Retrofit. Upon checking the function, it seems that most of the time is taken by the SpreadsheetApp.openById(getSpreadsheetId()) and sheet.getDataRange().getValues() methods.
I’m looking for a way to speed things up.