First Firebase integration - Time & Space Complexity
When connecting your app to Firebase for the first time, it's important to understand how the number of operations grows as you interact with the service.
We want to know: how does the work Firebase does change as we add more data or users?
Analyze the time complexity of the following operation sequence.
// Initialize Firebase app
const app = initializeApp(firebaseConfig);
// Get Firestore database
const db = getFirestore(app);
// Add multiple documents to a collection
for (let i = 0; i < n; i++) {
await setDoc(doc(db, "users", `user_${i}`), { name: `User ${i}` });
}
This code connects to Firebase and adds n user documents one by one to the database.
Identify the API calls, resource provisioning, data transfers that repeat.
- Primary operation: Writing a document to Firestore with
setDoc. - How many times: Exactly n times, once per user document.
Each new user means one more write operation to the database.
| 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 users added.
Time Complexity: O(n)
This means the time to add users grows in a straight line as you add more users.
[X] Wrong: "Adding many users at once only takes one operation."
[OK] Correct: Each user document requires its own write call, so the total work grows with the number of users.
Understanding how your Firebase calls scale helps you design apps that stay fast and reliable as they grow. This skill shows you can think about real-world app behavior.
"What if we batch all user writes into a single batch operation? How would the time complexity change?"