First GraphQL query - Time & Space Complexity
When we run a GraphQL query, it takes some time to get the data. We want to understand how this time changes when we ask for more data.
How does the work grow as the amount of data requested grows?
Analyze the time complexity of the following code snippet.
query {
books {
title
author {
name
}
}
}
This query asks for a list of books, each with its title and the author's name.
Look for parts that repeat work as data grows.
- Primary operation: Fetching each book and its author details.
- How many times: Once for every book in the list.
As you ask for more books, the work grows in a simple way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 books fetched |
| 100 | 100 books fetched |
| 1000 | 1000 books fetched |
Pattern observation: The work grows directly with the number of books requested.
Time Complexity: O(n)
This means the time to get results grows in a straight line as you ask for more books.
[X] Wrong: "The query time stays the same no matter how many books I ask for."
[OK] Correct: Each book requires fetching data, so more books mean more work and more time.
Understanding how query time grows helps you write better queries and explain your choices clearly in interviews.
"What if we added a nested list of reviews for each book? How would the time complexity change?"