0
0
GraphQLquery~5 mins

Union types in GraphQL - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Union types
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

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
1010 type checks and field fetches
100100 type checks and field fetches
10001000 type checks and field fetches

Pattern observation: The work grows directly with the number of items; doubling items doubles work.

Final Time Complexity

Time Complexity: O(n)

This means the time to get results grows in a straight line with the number of items returned.

Common Mistake

[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.

Interview Connect

Understanding how union types affect query time helps you explain how your API handles mixed data efficiently and scales well as data grows.

Self-Check

"What if the union included more types? How would the time complexity change?"