Expression-bodied lambdas in C Sharp (C#) - Time & Space Complexity
We want to understand how the time it takes to run expression-bodied lambdas changes as the input grows.
Specifically, how does the number of operations scale when using these lambdas in code?
Analyze the time complexity of the following code snippet.
Func square = x => x * x;
int[] numbers = {1, 2, 3, 4, 5};
foreach (var num in numbers)
{
Console.WriteLine(square(num));
}
This code defines a simple expression-bodied lambda to square a number and applies it to each item in an array.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The foreach loop that calls the lambda for each number.
- How many times: Once for each element in the array.
As the number of elements increases, the lambda runs once per element.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 calls to the lambda |
| 100 | 100 calls to the lambda |
| 1000 | 1000 calls to the lambda |
Pattern observation: The total work grows directly with the number of items.
Time Complexity: O(n)
This means the time to complete grows in a straight line as the input size grows.
[X] Wrong: "Expression-bodied lambdas run faster and reduce time complexity."
[OK] Correct: The lambda syntax is just a shorter way to write code; it does not change how many times the operation runs.
Understanding how lambdas affect time helps you explain your code clearly and shows you know how code scales with input size.
"What if the lambda called another function inside it? How would that affect the time complexity?"