Document ID strategies in Firebase - Time & Space Complexity
When working with Firebase, how you choose document IDs affects how many operations happen as your data grows.
We want to understand how the number of operations changes when adding many documents with different ID strategies.
Analyze the time complexity of adding documents with auto-generated IDs versus custom IDs.
// Adding documents with auto-generated IDs
for (let i = 0; i < n; i++) {
firestore.collection('items').add({ value: i });
}
// Adding documents with custom IDs
for (let i = 0; i < n; i++) {
firestore.collection('items').doc('item_' + i).set({ value: i });
}
This code adds n documents either letting Firebase create IDs or using custom IDs.
Look at what repeats as n grows:
- Primary operation: Writing a document to Firestore.
- How many times: Exactly n times, once per document.
The main difference is how IDs are assigned, but each write is still one operation.
As you add more documents, the number of write operations grows directly with n.
| Input Size (n) | Approx. API Calls/Operations |
|---|---|
| 10 | 10 writes |
| 100 | 100 writes |
| 1000 | 1000 writes |
Each new document means one more write, so the total grows steadily as you add more.
Time Complexity: O(n)
This means the total number of operations grows in direct proportion to the number of documents added.
[X] Wrong: "Using custom IDs will reduce the number of write operations compared to auto-generated IDs."
[OK] Correct: Both methods write one document per operation; the ID choice does not reduce the number of writes.
Understanding how document ID strategies affect operation counts helps you design scalable Firebase apps and shows you think about cost and performance.
What if you batch multiple document writes together? How would that change the time complexity?