0
0
Firebasecloud~5 mins

Adding documents (add vs set) in Firebase - Performance Comparison

Choose your learning style9 modes available
Time Complexity: Adding documents (add vs set)
O(n)
Understanding Time Complexity

When adding documents in Firebase, it's important to know how the time to complete the operation changes as you add more documents.

We want to understand how the number of documents affects the work Firebase does when using add() versus set().

Scenario Under Consideration

Analyze the time complexity of adding multiple documents using add() and set().


const collectionRef = firestore.collection('users');

// Using add() to add a new document with auto ID
collectionRef.add({ name: 'Alice', age: 30 });

// Using set() to add or overwrite a document with a known ID
collectionRef.doc('user123').set({ name: 'Bob', age: 25 });

// Adding multiple documents in a loop
for (let i = 0; i < n; i++) {
  collectionRef.add({ index: i });
}
    

This code adds documents to a collection, either letting Firebase create an ID or specifying one, repeated n times.

Identify Repeating Operations

Look at what happens repeatedly when adding documents.

  • Primary operation: Each call to add() or set() sends one write request to Firebase.
  • How many times: The write request happens once per document added, so n times for n documents.
How Execution Grows With Input

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

Input Size (n)Approx. Api Calls/Operations
1010 write requests
100100 write requests
10001000 write requests

Pattern observation: The work grows in a straight line with the number of documents added.

Final Time Complexity

Time Complexity: O(n)

This means the time to add documents grows directly in proportion to how many documents you add.

Common Mistake

[X] Wrong: "Using add() is faster than set() because it auto-generates IDs."

[OK] Correct: Both add() and set() send one write request per document, so their time grows the same way with the number of documents.

Interview Connect

Understanding how adding documents scales helps you design apps that handle data efficiently and predict costs as your app grows.

Self-Check

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