0
0
C Sharp (C#)programming~5 mins

Expression-bodied lambdas in C Sharp (C#) - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Expression-bodied lambdas
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

As the number of elements increases, the lambda runs once per element.

Input Size (n)Approx. Operations
1010 calls to the lambda
100100 calls to the lambda
10001000 calls to the lambda

Pattern observation: The total work grows directly with the number of items.

Final Time Complexity

Time Complexity: O(n)

This means the time to complete grows in a straight line as the input size grows.

Common Mistake

[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.

Interview Connect

Understanding how lambdas affect time helps you explain your code clearly and shows you know how code scales with input size.

Self-Check

"What if the lambda called another function inside it? How would that affect the time complexity?"