Response envelope patterns in Rest API - Time & Space Complexity
When using response envelope patterns in REST APIs, it's important to understand how the time to create and send responses changes as the data grows.
We want to know how the work done by the server grows when wrapping data in an envelope.
Analyze the time complexity of the following code snippet.
function getResponse(data) {
return {
status: "success",
count: data.length,
results: data
};
}
This code wraps the data array inside a response envelope with status and count fields.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Accessing the length of the data array and including the data itself in the response.
- How many times: The data array is referenced once; no explicit loops or traversals happen here.
As the size of the data array grows, the server must handle more data to include in the response.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Handling 10 data items |
| 100 | Handling 100 data items |
| 1000 | Handling 1000 data items |
Pattern observation: The work grows directly with the number of data items included in the response.
Time Complexity: O(n)
This means the time to prepare the response grows linearly with the number of items in the data.
[X] Wrong: "Wrapping data in an envelope adds no extra time cost regardless of data size."
[OK] Correct: Even though the envelope fields are fixed, including the entire data array means the server processes all items, so time grows with data size.
Understanding how response envelopes affect time complexity helps you explain API design choices clearly and shows you can think about performance as data scales.
"What if the response envelope included a nested loop to process each data item further? How would the time complexity change?"