0
0
Firebasecloud~5 mins

Creating collections and documents in Firebase - Performance & Efficiency

Choose your learning style9 modes available
Time Complexity: Creating collections and documents
O(n)
Understanding Time Complexity

When we create collections and documents in Firebase, we want to know how the time it takes changes as we add more data.

We ask: How does the number of operations grow when we add many documents?

Scenario Under Consideration

Analyze the time complexity of the following operation sequence.


const db = getFirestore();
for (let i = 0; i < n; i++) {
  const docRef = doc(collection(db, 'users'));
  await setDoc(docRef, { name: `User ${i}`, age: 20 + i });
}
    

This code creates a new document inside the 'users' collection for each user, setting simple data.

Identify Repeating Operations

Identify the API calls, resource provisioning, data transfers that repeat.

  • Primary operation: Calling setDoc to write each document.
  • How many times: Exactly once per document, so n times.
How Execution Grows With Input

Each new document requires one write operation, so as the number of documents grows, the total operations grow the same way.

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

Pattern observation: The number of operations grows directly with the number of documents added.

Final Time Complexity

Time Complexity: O(n)

This means the time to create documents grows in a straight line as you add more documents.

Common Mistake

[X] Wrong: "Creating multiple documents happens all at once, so time stays the same no matter how many documents."

[OK] Correct: Each document write is a separate operation that takes time, so more documents mean more total time.

Interview Connect

Understanding how operations grow helps you design efficient data writes and shows you can think about scaling in real projects.

Self-Check

"What if we batch all document writes into a single batch operation? How would the time complexity change?"