Creating collections and documents in Firebase - Performance & Efficiency
When we create collections and documents in Firebase, we want to know how the time it takes changes as we add more data.
We ask: How does the number of operations grow when we add many documents?
Analyze the time complexity of the following operation sequence.
const db = getFirestore();
for (let i = 0; i < n; i++) {
const docRef = doc(collection(db, 'users'));
await setDoc(docRef, { name: `User ${i}`, age: 20 + i });
}
This code creates a new document inside the 'users' collection for each user, setting simple data.
Identify the API calls, resource provisioning, data transfers that repeat.
- Primary operation: Calling
setDocto write each document. - How many times: Exactly once per document, so
ntimes.
Each new document requires one write operation, so as the number of documents grows, the total operations grow the same way.
| Input Size (n) | Approx. API Calls/Operations |
|---|---|
| 10 | 10 writes |
| 100 | 100 writes |
| 1000 | 1000 writes |
Pattern observation: The number of operations grows directly with the number of documents added.
Time Complexity: O(n)
This means the time to create documents grows in a straight line as you add more documents.
[X] Wrong: "Creating multiple documents happens all at once, so time stays the same no matter how many documents."
[OK] Correct: Each document write is a separate operation that takes time, so more documents mean more total time.
Understanding how operations grow helps you design efficient data writes and shows you can think about scaling in real projects.
"What if we batch all document writes into a single batch operation? How would the time complexity change?"