Filtering arguments in GraphQL - Time & Space Complexity
When using filtering arguments in GraphQL queries, it's important to understand how the time to get results changes as the data grows.
We want to know how the filtering affects the work the server does as more data is added.
Analyze the time complexity of the following GraphQL query with filtering arguments.
query GetBooksByAuthor($authorName: String!) {
books(filter: { author: $authorName }) {
id
title
author
}
}
This query fetches books written by a specific author using a filter argument.
Look for repeated steps that happen as the data grows.
- Primary operation: Checking each book to see if the author matches the filter.
- How many times: Once for every book in the database.
As the number of books increases, the server checks more items to find matches.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks |
| 100 | 100 checks |
| 1000 | 1000 checks |
Pattern observation: The work grows directly with the number of books.
Time Complexity: O(n)
This means the time to get results grows in a straight line as the number of books grows.
[X] Wrong: "Filtering arguments instantly find the data without checking all items."
[OK] Correct: The server usually checks each item to see if it matches the filter, so time grows with data size.
Understanding how filtering affects query time helps you explain how APIs handle data efficiently and shows you think about performance in real projects.
What if the books were indexed by author? How would that change the time complexity?