Lambda handler function structure in AWS - Time & Space Complexity
We want to see how the time to run a Lambda function changes as the input size grows.
Specifically, how many times the function's main steps run when handling different input sizes.
Analyze the time complexity of this Lambda handler function.
exports.handler = async (event) => {
const results = [];
for (const item of event.items) {
// Simulate processing each item
results.push(processItem(item));
}
return results;
};
function processItem(item) {
// Simple processing logic
return item.value * 2;
}
This function processes each item in the input list by doubling its value.
Look at what repeats as input grows.
- Primary operation: Calling
processItemfor each item. - How many times: Once for every item in
event.items.
As the number of items grows, the function does more work.
| Input Size (n) | Approx. Api Calls/Operations |
|---|---|
| 10 | 10 calls to processItem |
| 100 | 100 calls to processItem |
| 1000 | 1000 calls to processItem |
Pattern observation: The work grows directly with the number of items.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of items.
[X] Wrong: "The function runs in the same time no matter how many items there are."
[OK] Correct: Each item needs processing, so more items mean more work and more time.
Understanding how your Lambda function scales with input size shows you can write efficient cloud code that handles growth smoothly.
"What if the function called another API inside the loop for each item? How would the time complexity change?"