首页 > 解决方案 > Firebase 更新功能有时执行较慢

问题描述

我有一个简单的更新功能,与其他时间相比,它有时执行得非常慢。

// Five executions with very different execution times
Finished in 1068ms // Almost six times slower than the next execution
Finished in 184ms
Finished in 175ms
Finished in 854ms
Finished in 234ms

该函数是从前端触发的,并且不在 Firebase Cloud Functions 上运行。

const startAt = performance.now()
const db = firebase.firestore();
const ref = db.doc(`random/nested/document/${id}`);
ref.update({
        na: boolean // a calculated boolean with array.includes(...)
          ? firebase.firestore.FieldValue.arrayRemove(referenceId)
          : firebase.firestore.FieldValue.arrayUnion(referenceId)
      })
      .then(() => {
        let endAt = performance.now();
        console.log("Finished in " + (endAt - startAt) + "ms");
      });

有什么我可以改进来解决这些性能差异的吗?

此外,更长的执行时间不仅会出现在从数组中删除某些内容或向数组中添加某些内容时。它出现在添加和删除时。有时这些执行时间会达到 3000 毫秒。

标签: javascriptreactjsfirebasegoogle-cloud-firestore

解决方案


与冷启动 Cloud Function 类似,其中所有内容都已启动、初始化并准备好使用,与 Cloud Firestore 的连接也需要通过 DNS 解析,需要获取 ID 令牌来验证请求,以及到服务器的套接字打开并在服务器和 SDK 之间交换任何握手。

数据库上的任何新操作都可以利用先前用于初始化连接的工作,这就是它们看起来更快的原因。

将其显示为松散的伪代码:

let connection = undefined;
function initConnectionToFirestore() {
  if (!connection) {
    await loadFirebaseConfig();
    await Promise.all([
      resolveIpAddressOfFirebaseAuth(),
      resolveIpAddressOfFirestoreInstance()
    ]);
    await getIdTokenFromFirebaseAuth();
    await addAuthenticationToRequest();
    connection = await openConnection();
  }
  return connection;
}

function doUpdate(...args) {
  const connection = await initConnectionToFirestore();
  // do the work
  connection.send(/* ... */);
}

await doUpdate() // has to do work of initConnectionToFirestore
await doUpdate() // reuses previous work
await doUpdate() // reuses previous work
await doUpdate() // reuses previous work

推荐阅读