0
0
Firebasecloud~5 mins

Array update operations (arrayUnion, arrayRemove) in Firebase - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Array update operations (arrayUnion, arrayRemove)
O(n)
Understanding Time Complexity

When updating arrays in Firebase, it's important to know how the time taken grows as the array gets bigger.

We want to understand how the operations arrayUnion and arrayRemove behave as more items are involved.

Scenario Under Consideration

Analyze the time complexity of these Firebase array update operations.


const docRef = firestore.collection('users').doc('user1');

// Add items to array if not present
await docRef.update({
  tags: firebase.firestore.FieldValue.arrayUnion('newTag')
});

// Remove items from array if present
await docRef.update({
  tags: firebase.firestore.FieldValue.arrayRemove('oldTag')
});
    

This code adds or removes elements from an array field in a Firestore document.

Identify Repeating Operations

Look at what happens repeatedly when these operations run.

  • Primary operation: Checking if the item exists in the array and then adding or removing it.
  • How many times: This check happens for each element in the array during the update.
How Execution Grows With Input

As the array size grows, the time to check and update grows too.

Input Size (n)Approx. Api Calls/Operations
10About 10 checks to find or remove the item
100About 100 checks
1000About 1000 checks

Pattern observation: The number of checks grows directly with the array size.

Final Time Complexity

Time Complexity: O(n)

This means the time to add or remove an item grows linearly with the number of items in the array.

Common Mistake

[X] Wrong: "Adding or removing an item from the array is always instant, no matter the size."

[OK] Correct: Firebase must check the whole array to avoid duplicates or to find the item to remove, so bigger arrays take more time.

Interview Connect

Understanding how array updates scale helps you explain performance in real apps and shows you think about efficient data handling.

Self-Check

What if Firebase stored arrays as sets internally? How would that change the time complexity of arrayUnion and arrayRemove?