0
0
GraphQLquery~5 mins

Inline fragments in GraphQL - Time & Space Complexity

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

Scenario Under Consideration

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

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

As the number of items grows, the server checks each item's type and fetches the matching fields.

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

Common Mistake

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

Interview Connect

Understanding how inline fragments affect query time helps you explain how GraphQL handles different data shapes efficiently.

Self-Check

"What if the number of inline fragments grows with the number of types? How would the time complexity change?"