Nested objects and arrays in Firebase - Time & Space Complexity
When working with nested objects and arrays in Firebase, it's important to understand how the time to read or write data grows as the data size increases.
We want to know how the number of operations changes when the nested data gets bigger.
Analyze the time complexity of the following operation sequence.
const docRef = firestore.collection('users').doc('user123');
const snapshot = await docRef.get();
const nestedData = snapshot.data().orders;
nestedData.forEach(order => {
console.log(order.items.length);
});
This code reads a user's document, accesses a nested array of orders, and then loops through each order to check the number of items inside.
Identify the API calls, resource provisioning, data transfers that repeat.
- Primary operation: Reading the document once from Firestore.
- How many times: The document read happens once, but iterating over the nested array happens once per order.
As the number of orders grows, the loop runs more times, increasing the operations linearly.
| Input Size (n) | Approx. Api Calls/Operations |
|---|---|
| 10 orders | 1 document read + 10 loop operations |
| 100 orders | 1 document read + 100 loop operations |
| 1000 orders | 1 document read + 1000 loop operations |
Pattern observation: The document read stays the same, but the loop operations grow directly with the number of orders.
Time Complexity: O(n)
This means the time to process grows directly in proportion to the number of nested orders.
[X] Wrong: "Reading the document once means the time is always constant no matter how big the nested data is."
[OK] Correct: Even though the document read is one operation, processing nested arrays inside requires looping through each element, which takes more time as the array grows.
Understanding how nested data affects operation counts helps you explain performance clearly and shows you can reason about real-world data structures.
"What if we changed the nested array to a nested object with keys instead of an array? How would the time complexity change when accessing all items?"