AppsScriptPulse

Memoization in Apps Script with Cache Service

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:

First run (cold start) and second run (warm start) with better performance for cached results first call

Source: Memoization in Apps Script | Justin Poehnelt

Leave a Reply

Your email address will not be published. Required fields are marked *