Inline fragments in GraphQL - Time & Space Complexity
When using inline fragments in GraphQL, we want to know how the time to get data changes as the data grows.
We ask: How does the work grow when the number of items or types increases?
Analyze the time complexity of the following code snippet.
query {
searchItems {
id
... on Book {
author
pages
}
... on Movie {
director
duration
}
}
}
This query fetches a list of items, and for each item, it fetches fields depending on the item type using inline fragments.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each item in the searchItems list.
- How many times: Once for each item returned by the search.
As the number of items grows, the server checks each item's type and fetches the matching fields.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 type checks and field fetches |
| 100 | 100 type checks and field fetches |
| 1000 | 1000 type checks and field fetches |
Pattern observation: The work grows directly with the number of items; doubling items doubles the work.
Time Complexity: O(n)
This means the time to get results grows in a straight line with the number of items.
[X] Wrong: "Using inline fragments makes the query slower exponentially because it checks many types."
[OK] Correct: Each item is checked once for its type, so the work grows only with the number of items, not the number of types.
Understanding how inline fragments affect query time helps you explain how GraphQL handles different data shapes efficiently.
"What if the number of inline fragments grows with the number of types? How would the time complexity change?"