0
0
Firebasecloud~5 mins

Document ID strategies in Firebase - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Document ID strategies
O(n)
Understanding Time Complexity

When working with Firebase, how you choose document IDs affects how many operations happen as your data grows.

We want to understand how the number of operations changes when adding many documents with different ID strategies.

Scenario Under Consideration

Analyze the time complexity of adding documents with auto-generated IDs versus custom IDs.


// Adding documents with auto-generated IDs
for (let i = 0; i < n; i++) {
  firestore.collection('items').add({ value: i });
}

// Adding documents with custom IDs
for (let i = 0; i < n; i++) {
  firestore.collection('items').doc('item_' + i).set({ value: i });
}
    

This code adds n documents either letting Firebase create IDs or using custom IDs.

Identify Repeating Operations

Look at what repeats as n grows:

  • Primary operation: Writing a document to Firestore.
  • How many times: Exactly n times, once per document.

The main difference is how IDs are assigned, but each write is still one operation.

How Execution Grows With Input

As you add more documents, the number of write operations grows directly with n.

Input Size (n)Approx. API Calls/Operations
1010 writes
100100 writes
10001000 writes

Each new document means one more write, so the total grows steadily as you add more.

Final Time Complexity

Time Complexity: O(n)

This means the total number of operations grows in direct proportion to the number of documents added.

Common Mistake

[X] Wrong: "Using custom IDs will reduce the number of write operations compared to auto-generated IDs."

[OK] Correct: Both methods write one document per operation; the ID choice does not reduce the number of writes.

Interview Connect

Understanding how document ID strategies affect operation counts helps you design scalable Firebase apps and shows you think about cost and performance.

Self-Check

What if you batch multiple document writes together? How would that change the time complexity?