In the following example, functionB doesn't use anything from the global scope, yet its cold start time is increased due to the initialization of the global scope needed for functionA.
const functions = require('@google-cloud/functions-framework');
const {lightComputation, heavyComputation} = require('./computations');
// Global (instance‐wide) scope
const instanceVar = heavyComputation();
/**
* HTTP function A
*/
functions.http('functionA', (req, res) => {
const functionVar = lightComputation();
res.send(`A: instance=${instanceVar}, function=${functionVar}`);
});
/**
* HTTP function B
* (does *not* use instanceVar at all)
*/
functions.http('functionB', (req, res) => {
const functionVar = lightComputation();
res.send(`B: function=${functionVar}`);
});
I have tried to move the call of heavyComputation()
in functionA, but we will lose the performance optimization, as explained in the docs
This way you can cache objects that may be expensive to recreate on each function invocation. Moving such objects from the function body to global scope may result in significant performance improvements.
Is there a way to have a global scope initialized only for specific functions? Or even multiple global scopes for different functions?
You can simply assign the result of heavyComputation
to a global non-const variable (let
), gated by a check to see if the work has previously been done in the first invocation of function A (once for any given server instance that might be allocated for it).
let instanceVar = undefined;
/**
* HTTP function A
*/
functions.http('functionA', (req, res) => {
if (instanceVar === undefined) {
instanceVar = heavyComputation()
}
});