Reputation: 1147
I have written a code. To run the code I have declared quite a few variables. Now that I finished, I realised that I did not have to declare the variables as I can call on what the variable is supposed to call for directly within the function.
Example:
function test() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var date = Utilities.formatDate(new Date(), "GMT", "dd-MMM-yyyy");
sheet.appendRow(date);
}
I could have not declared date and written this:
function test() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
sheet.appendRow(Utilities.formatDate(new Date(), "GMT", "dd-MMM-yyyy"));
}
Which of those is considered best practice and better for performance of app?
Thanks
Upvotes: 0
Views: 669
Reputation: 8406
The effect on performance will be negligible. You should write it the way that is most readable. In your case that is debatable, but I like declaring the date
variable since it makes the subsequent line much shorter and less overwhelming.
A case where it could affect performance would be if you were consuming the date in multiple locations. Then, you would want to declare a variable. For example...
function test() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
sheet.appendRow(Utilities.formatDate(new Date(), "GMT", "dd-MMM-yyyy"));
somethingElse(Utilities.formatDate(new Date(), "GMT", "dd-MMM-yyyy"));
}
Aside from violating the DRY principle, the above hurts performance because you are doing the work twice (creating a Date object and formatting it).
In summary, if you are only consuming the value once, you don't need to make it a variable, but you should if it improves readability.
Upvotes: 2