Document-collection data model in Firebase - Time & Space Complexity
When working with Firebase's document-collection model, it is important to understand how the time to access or query data changes as your data grows.
We want to know how the number of operations changes when we read or write documents in collections.
Analyze the time complexity of the following code snippet.
const collectionRef = firestore.collection('users');
collectionRef.get().then(snapshot => {
snapshot.forEach(doc => {
console.log(doc.id, '=>', doc.data());
});
});
This code fetches all documents from the 'users' collection and prints each document's data.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each document in the collection snapshot.
- How many times: Once for each document in the 'users' collection.
As the number of documents in the collection grows, the time to fetch and process all documents grows proportionally.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 document reads and loops |
| 100 | About 100 document reads and loops |
| 1000 | About 1000 document reads and loops |
Pattern observation: The operations increase directly with the number of documents.
Time Complexity: O(n)
This means the time to read all documents grows linearly with the number of documents in the collection.
[X] Wrong: "Fetching a collection always takes the same time regardless of size."
[OK] Correct: The time depends on how many documents you read; more documents mean more work and longer time.
Understanding how data size affects read time in Firebase helps you design efficient queries and data structures, a valuable skill in real projects and interviews.
"What if we only fetched documents with a filter instead of the whole collection? How would the time complexity change?"