Fragments for reusable selections in GraphQL - Time & Space Complexity
When using fragments in GraphQL, we want to understand how the time to get data changes as the data grows.
We ask: How does using fragments affect the work done when fetching repeated fields?
Analyze the time complexity of the following GraphQL query using fragments.
query GetUsers {
users {
...UserDetails
}
}
fragment UserDetails on User {
id
name
email
}
This query fetches a list of users and reuses the same set of fields for each user using a fragment.
Look for repeated actions in the query execution.
- Primary operation: Fetching the fields inside the fragment for each user.
- How many times: Once for each user in the list.
As the number of users grows, the work to fetch their details grows too.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Fetching details for 10 users |
| 100 | Fetching details for 100 users |
| 1000 | Fetching details for 1000 users |
Pattern observation: The work grows directly with the number of users.
Time Complexity: O(n)
This means the time to get data grows in a straight line as the number of users grows.
[X] Wrong: "Using fragments makes the query run faster because it avoids repeating fields."
[OK] Correct: Fragments only help organize the query and avoid rewriting fields, but the server still fetches data for each user separately.
Understanding how repeated data fetching scales helps you explain performance in real projects and shows you know how queries behave as data grows.
What if the fragment included a nested list of posts for each user? How would the time complexity change?