Use global variables to reuse objects in future invocations

There is no guarantee that the state of a Cloud function will be preserved for future invocations. However, Cloud Functions often recycles the execution environment of a previous invocation. If you declare a variable with a global scope, its value can be reused in subsequent invocations without having to be recomputed.

This way, you can cache objects that may be expensive to recreate on each function invocation. Moving such objects from the function body to a global scope may result in significant performance improvements.

Get DevOps for Serverless Applications now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.