Home > Software engineering >  Best practice for declaring Google Apps Script variables
Best practice for declaring Google Apps Script variables

Time:03-18

I'm currently developing a Web App in Google Apps Script. I'm competent enough to get what I need done, but it's the first time I've developed anything at any sort of scale, and I'm looking for some guidance on best practice for performance (if it makes a difference at all).

I've got a number of variables (loading data from various sheets) that will be required to be accessed multiple times, by multiple functions. In the past, I've always declared these as constants outside of any function, so I can use any function to access them. For example:

const SS = SpreadsheetApp.getSpreadsheetById("spreadsheetId");
const SHEET1 = SS.getSheetByName("sheetName");
const DATA1 = SHEET.getRange(blah, blah, blah, blah).getValues();
const SHEET2 = SS.getSheetByName("sheetName");
const DATA2 = SHEET.getRange(blah, blah, blah, blah).getValues();

Both the sheet and data will be accessed multiple times by various functions. However, there's 6 or 7 sheets and sets of data that will be accessed by various functions. They will access multiple sets of data (or directly getRange from the sheet if they need a snippit), but no function will access all of them at once. Are those variables still loaded, even if the function doesn't require them?

For example, I have a function that runs onFormSubmit. I want that to run as fast as possible. It only accesses one of the 7 sheets. Will that be initializing all of the global variables when it runs, even though they're not required?

CodePudding user response:

Think I've managed to answer my own question. Using the debugger in the GAS IDE. One of my functions that only uses a snippit of the data looks like it's loading all of my variables.

CodePudding user response:

From the question

Are those variables still loaded, even if the function doesn't require them?

It depends. If the constants declared "outside of any function" (this is called global scope) and the functions belongs to the same project then the answer is yes, but if the constants are declared in a library, they will not be available for functions of the main project.

For example, I have a function that runs onFormSubmit. I want that to run as fast as possible. It only accesses one of the 7 sheets. Will that be initializing all of the global variables when it runs, even though they're not required?

Yes.


Since calls to Google Apps Script services are "expensive" in terms of execution time, in order to make your scripts efficient and considering that installable triggers have daily limit, avoid to make calls that aren't used on every function on the global scope.

  • Related