在某些情况下,冷启动会好吗? (云功能)

时间:2020-09-15 11:37:21

标签: javascript node.js firebase google-cloud-platform google-cloud-functions

我正在开发一个具有+100个云功能的项目,因此为了简化工作,我正在构造所有功能,如下所示:

/functions
    /src
        spotify/ 
            searchMusic.function.js
            ...
        auth/
            signUp.function.js
            ...

        ...

    index.js // Auto export every cloud function

在每个以.function.js结尾的文件中,我导出一个唯一的云函数。我的问题是,由于每个文件没有多个Google Cloud函数,我应该进行懒惰的导入/初始化吗?

例如,我知道当模块中有两个功能并且其中一个不使用另一个使用的软件包时,执行此操作很有用:

 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...{}
 

但是在我的情况下(我在f1.function.js中只有f1),惰性导入/初始化会减少冷启动吗?还是在全球范围内进行所有进口会更好?

谢谢。

更新

这就是我的意思:

"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...

1 个答案:

答案 0 :(得分:3)

但是在我的情况下(我在f1.function.js中只有f1),惰性导入/初始化会减少冷启动吗?

不,不会有任何改变。

在任何一种情况下(在全局范围内或在函数内运行),代码都位于处理第一个请求的关键路径中。更改范围不会更改该代码运行所花费的时间。

将代码移出全局范围唯一的帮助是,当您有多个不共享该代码的功能时。将该代码的执行移到该函数中只是为了确保其他函数不会不必要地执行它。

相关问题