Query variables in GraphQL - Time & Space Complexity
We want to understand how the time to run a GraphQL query changes when we use variables.
Specifically, how does the query's work grow as the input data or variables change?
Analyze the time complexity of the following GraphQL query using variables.
query GetUser($id: ID!) {
user(id: $id) {
name
posts {
title
comments {
text
}
}
}
}
This query fetches a user by ID, then gets their posts and comments on those posts.
Look for repeated actions in the query.
- Primary operation: Fetching posts and then comments for each post.
- How many times: For each post, all comments are fetched, so this repeats for every post.
As the number of posts and comments grows, the work grows too.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 posts, 5 comments each | About 10 + (10 x 5) = 60 operations |
| 100 posts, 5 comments each | About 100 + (100 x 5) = 600 operations |
| 1000 posts, 5 comments each | About 1000 + (1000 x 5) = 6000 operations |
Pattern observation: The total work grows roughly in proportion to the number of posts times the number of comments per post.
Time Complexity: O(p + p x c)
This means the time grows with the number of posts (p) plus the number of comments (c) per post multiplied by posts.
[X] Wrong: "Using variables makes the query always run in constant time."
[OK] Correct: Variables only change input values; the query still processes all posts and comments, so time depends on data size.
Understanding how query variables affect time helps you explain performance clearly and shows you know how data size impacts work.
What if we added a variable to limit the number of posts returned? How would that change the time complexity?