javascript - 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 毫秒。
解决方案
与冷启动 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
推荐阅读
- matlab - 默认的“图例”功能被意外覆盖
- android - 如何在 MODE_NIGHT_FOLLOW_SYSTEM 上刷新 AppWidget?
- powershell - 对包含重复值的列表进行分组
- python - 将 .xls 转换为 .xlsx 以便在 openpyxl 问题中处理
- c++ - 在 Qt 中显示带有关闭按钮的图像缩略图
- c++ - 在 Qt5 应用程序上读取 CSV 文件时出现无限循环
- jenkins - 运行 jenkins 作业以使用 Ansible 模板将 java 应用程序部署到 tomcat 服务器时出错
- javascript - 将日期和每个类别的最新项目保存在数组中
- c# - C# While 循环仅适用于消息框
- azure-cli - Azure CLI - Powershell