Increment operations in Firebase - Time & Space Complexity
When we increase a number stored in Firebase, we want to know how the work grows as we do more increments.
We ask: How does the time to update change when we do many increments?
Analyze the time complexity of the following operation sequence.
const incrementValue = 1;
const docRef = firestore.collection('counters').doc('countDoc');
for (let i = 0; i < n; i++) {
docRef.update({
count: firebase.firestore.FieldValue.increment(incrementValue)
});
}
This code increases a counter in a document by 1, repeating this update n times.
Identify the API calls, resource provisioning, data transfers that repeat.
- Primary operation: The update call to increment the counter field.
- How many times: This update is called once for each increment, so n times.
Each increment sends one update request. So if you do 10 increments, you have 10 update calls.
| Input Size (n) | Approx. Api Calls/Operations |
|---|---|
| 10 | 10 update calls |
| 100 | 100 update calls |
| 1000 | 1000 update calls |
Pattern observation: The number of update calls grows directly with the number of increments.
Time Complexity: O(n)
This means the time to complete all increments grows in a straight line as you add more increments.
[X] Wrong: "Incrementing a counter multiple times is just one operation because it's the same field."
[OK] Correct: Each increment sends a separate update request, so each one takes time and resources.
Understanding how repeated updates affect performance helps you design efficient cloud apps and shows you can think about real-world costs.
"What if we combined all increments into a single update call? How would the time complexity change?"