Reputation: 2641
I am developing a project which will have +100 cloud functions, so for making the work easier I am structuring all my functions like this:
/functions
/src
spotify/
searchMusic.function.js
...
auth/
signUp.function.js
...
...
index.js // Auto export every cloud function
In each file that ends with .function.js I export an unique cloud function. My question is that, as I don't have more than one google cloud function per file, should I make lazy imports/initializations?
For example, I know that it is useful to do this when there are two functions in a module and one of them doesn't use a package which is used in the other:
const is_f1_admin_initialized = false;
exports.f1 = functions.region...{
const admin = require("firebase-admin");
// Lazy initialization
if(!is_f1_admin_initialized) {
// Initialize the admin SDK
...
is_f1_admin_initialized = true;
}
}
exports.f2 = functions.region...{}
But in my situation, where I only have f1 in f1.function.js, will lazy imports/initializations reduce the cold start? Or will it be better to make all imports in the global scope?
Thank you.
That's what I mean:
"use-strict";
const functions = require("firebase-functions");
const admin = require("firebase-admin");
// All my imports...
// The admin SDK can only be initialized once.
try {
const googleCloudServiceAccount = require("../../utils/json/googleCloudServiceAccount.json");
admin.initializeApp({
...
});
} catch (e) {}
// The unique cloud function in the module
exports.function = functions.region...
// All my helper functions...
Upvotes: 1
Views: 96
Reputation: 317352
But in my situation, where I only have f1 in f1.function.js, will lazy imports/initializations reduce the cold start?
No, it will make no difference.
In either case (running in either the global scope, or within the function), the code is in the critical path of serving the first request. Changing the scope doesn't change the time it takes for that code to run.
The only time that moving code out of the global scope will help is when you have multiple functions that do not share that code. Moving the execution of that code into the function simply ensures that other functions don't unnecessarily execute it.
Upvotes: 4