0
0
Firebasecloud~5 mins

Why Realtime Database differs from Firestore in Firebase - Performance Analysis

Choose your learning style9 modes available
Time Complexity: Why Realtime Database differs from Firestore
O(n)
Understanding Time Complexity

We want to understand how the speed of data operations changes when using Realtime Database versus Firestore.

How does the number of operations grow as we work with more data?

Scenario Under Consideration

Analyze the time complexity of reading multiple records from each database.


// Realtime Database
const ref = firebase.database().ref('items');
ref.once('value').then(snapshot => {
  snapshot.forEach(child => {
    console.log(child.key, child.val());
  });
});

// Firestore
const collection = firebase.firestore().collection('items');
collection.get().then(querySnapshot => {
  querySnapshot.forEach(doc => {
    console.log(doc.id, doc.data());
  });
});
    

This code reads all items from a list in each database and logs their data.

Identify Repeating Operations

Look at what happens repeatedly when reading data.

  • Primary operation: Processing each item's data.
  • How many times: Once per item in the list.
How Execution Grows With Input

As the number of items grows, the number of operations grows too.

Input Size (n)Approx. Operations
10About 10 operations
100About 100 operations
1000About 1000 operations

Each item requires a separate operation, so the work grows directly with the number of items.

Final Time Complexity

Time Complexity: O(n)

This means the time to read all items grows in a straight line as the number of items increases.

Common Mistake

[X] Wrong: "Fetching data from Firestore or Realtime Database always takes the same time no matter how many items there are."

[OK] Correct: Each item requires a separate operation, so more items mean more work and longer time.

Interview Connect

Understanding how data operations scale helps you design apps that stay fast as they grow. This skill shows you can think about real-world app performance.

Self-Check

What if we used queries to limit the number of items fetched? How would that change the time complexity?