Link headers for navigation in Rest API - Time & Space Complexity
We want to understand how the time to process link headers changes as the number of links grows.
How does adding more navigation links affect the work done by the server or client?
Analyze the time complexity of the following code snippet.
// Example of setting Link headers for navigation
const links = [
{ rel: 'next', url: '/page/2' },
{ rel: 'prev', url: '/page/0' },
{ rel: 'first', url: '/page/1' },
{ rel: 'last', url: '/page/10' }
];
const linkHeader = links.map(link => `<${link.url}>; rel="${link.rel}"`).join(', ');
response.setHeader('Link', linkHeader);
This code builds a Link header string by looping through an array of navigation links and joining them into one header.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the array of link objects with
map. - How many times: Once for each link in the array.
As the number of links increases, the time to build the header grows in a straight line.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 string creations and joins |
| 100 | 100 string creations and joins |
| 1000 | 1000 string creations and joins |
Pattern observation: The work grows directly with the number of links; double the links, double the work.
Time Complexity: O(n)
This means the time to build the Link header grows linearly with the number of navigation links.
[X] Wrong: "Adding more links won't affect performance much because it's just a header."
[OK] Correct: Even small repeated tasks add up; more links mean more string operations and longer processing time.
Understanding how simple loops affect performance helps you explain API design choices clearly and shows you think about efficiency in real projects.
"What if we cached the Link header string instead of rebuilding it every time? How would the time complexity change?"