Union types in GraphQL - Time & Space Complexity
When using union types in GraphQL, we want to understand how the time to get results changes as the data grows.
We ask: How does the query time grow when we have more items of different types combined?
Analyze the time complexity of the following code snippet.
query {
search(term: "apple") {
... on Fruit {
name
sweetness
}
... on Vegetable {
name
color
}
}
}
This query searches for items that can be either Fruit or Vegetable and fetches fields based on their type.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The server loops through each item in the search results to check its type and fetch fields.
- How many times: Once for each item returned by the search.
As the number of search results grows, the server does more work for each item to determine its type and fetch data.
| 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 work.
Time Complexity: O(n)
This means the time to get results grows in a straight line with the number of items returned.
[X] Wrong: "Using union types makes the query slower exponentially because it checks many types."
[OK] Correct: The server checks each item once; it does not multiply work by the number of types, so growth is linear, not exponential.
Understanding how union types affect query time helps you explain how your API handles mixed data efficiently and scales well as data grows.
"What if the union included more types? How would the time complexity change?"