英文:
firestore : is it faster to retrieve a document by its id or by a query?
问题
以下是您要翻译的内容:
我的收藏中的文档有一个ID(当然),还有一个字段,其中保存了相同的ID。
问题:通过文档的ID来检索文档是更快的还是通过查询更快?
collection.doc(id).get().then(....)
还是通过查询:
collection.where('id', '==', id).get().then(...)
我刚刚重构了我的函数代码。我过去使用查询,但现在我直接使用集合中文档的ID。但我有一种直接方法需要更长时间的印象。我只是想知道这是否只是一个印象...
英文:
The documents in my collection have an id (of course), but also a field in which the same id is kept.
Question : is it faster to retrieve that document by its id
collection.doc(id).get().then(....)
or by a query
collection.where('id', '==', id).get().then(...)
I just refactored my functions-code. I used to use a query, but now I'm using the id of the document in the collection directly. But I have the impression that this direct method takes longer. I just wonder if that is just an impression ...
答案1
得分: 1
在理论上,这两者在性能上没有区别。Firestore 查询的性能与查询返回的文档数量成比例。如果两个查询都返回1个文档,那么它们应该表现相同。它们实际上都使用索引来查找唯一的值。
参见:https://stackoverflow.com/questions/46603205/queries-scale-with-the-size-of-your-result-set-not-the-size-of-your-data-set
如果你真的想要在这方面进行微基准测试,你应该自己进行测试,找出哪个更快。但我认为你可能会花费很多时间来优化不需要优化的东西。你可以自行决定是否值得这样做。
我的建议:不要过多担心性能,而应该关注代码的清晰度。在你阅读代码的上下文时,哪一个更容易理解呢?通常,对文档引用进行单独的获取操作更短且更容易阅读,不需要在期望只有一个文档时查看文档结果的数组,但你的观点可能不同。
英文:
In theory, there is no difference in performance between the two. Firestore queries scale with the number of documents returned by the query. If both queries return 1 document, then they should perform the same. They are essentially both using an index to find a unique value.
If you really want a micro-benchmark on this, you should perform your own tests to find out which is faster. But I think you'll be spending a lot of time optimizing something that doesn't need to be optimized. You can decide for yourself if that's worth your time.
My opinionated advice: Instead of worrying about performance, you should worry about clarity of your code. Which one makes more sense to you when you read it in the context of your program? Usually a single get on a document reference is shorter and easier to read, and doesn't require you to look at an array of document results when you expect only one document, but your opinion might be different.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论