A generic Apps Script memoization function can be written to cache any function.
We’ve featured a couple of Apps Script optimisation techniques in the past. This example from Justin Poehnelt uses a technique found in many coding syntaxes of ‘memoization‘:
In computing, memoization or memoisation is an optimization technique used primarily to speed up computer programs by storing the results of expensive function calls to pure functions and returning the cached result when the same inputs occur again
For more background on when and why you might use ‘memorization’ you can read about Memorization [sic] in JavaScript. In the case of Google Apps Script developers have opportunities to integrate the built-in Cache Service and Properties Service to memorize function results in the context of the script, document or the user.
In the example provided in the source post by Justin it defaults to CacheService.getScriptCache()
to store the memoized results but it would be easy to change this to CacheService.getUserCache()
or CacheService.getDocumentCache()
. With a little modification you could also include Properties Service.
To help you see how memoization works here’s a gist for both pure JavaScript and Apps Script techniques which you can copy and run in the Apps Script Editor. The results hopefully speak for themselves:
Source: Memoization in Apps Script | Justin Poehnelt
Member of Google Developers Experts Program for Google Workspace (Google Apps Script) and interested in supporting Google Workspace Devs.