【问题标题】:Can cold starts be good in some cases? (Cloud Functions)在某些情况下冷启动会好吗? (云功能)
【发布时间】:2026-01-20 17:20:06
【问题描述】:

我正在开发一个具有 +100 个云功能的项目,因此为了使工作更轻松,我将我的所有功能都这样构建:

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

        ...

    index.js // Auto export every cloud function

在每个以 .function.js 结尾的文件中,我导出一个独特的云函数。我的问题是,由于每个文件没有多个谷歌云功能,我应该进行惰性导入/初始化吗?

例如,我知道当一个模块中有两个函数并且其中一个不使用另一个中使用的包时这样做很有用:

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

【问题讨论】:

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


    【解决方案1】:

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

    不,不会有什么不同。

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

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

    【讨论】: