Adding documents (add vs set) in Firebase - Performance Comparison
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().
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.
Look at what happens repeatedly when adding documents.
- Primary operation: Each call to
add()orset()sends one write request to Firebase. - How many times: The write request happens once per document added, so n times for n documents.
As you add more documents, the number of write requests grows directly with the number of documents.
| Input Size (n) | Approx. Api Calls/Operations |
|---|---|
| 10 | 10 write requests |
| 100 | 100 write requests |
| 1000 | 1000 write requests |
Pattern observation: The work grows in a straight line with the number of documents added.
Time Complexity: O(n)
This means the time to add documents grows directly in proportion to how many documents you add.
[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.
Understanding how adding documents scales helps you design apps that handle data efficiently and predict costs as your app grows.
"What if we batch multiple document writes together? How would that change the time complexity?"