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

Func delegate type in C Sharp (C#) - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Func delegate type
O(n)
Understanding Time Complexity

We want to understand how the time it takes to run code using the Func delegate changes as the input size grows.

Specifically, how does calling a Func repeatedly affect performance?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


Func<int, int> square = x => x * x;
int n = 10; // example size
int[] numbers = new int[n];
int[] results = new int[n];
for (int i = 0; i < n; i++)
{
    results[i] = square(numbers[i]);
}
    

This code uses a Func delegate to square each number in an array and stores the results.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Calling the Func delegate inside a for loop.
  • How many times: Exactly once for each element in the input array, so n times.
How Execution Grows With Input

Each time we add one more number, we call the Func one more time.

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

Pattern observation: The number of operations grows directly with the input size.

Final Time Complexity

Time Complexity: O(n)

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

Common Mistake

[X] Wrong: "Using a Func delegate makes the code slower in a way that changes the time complexity."

[OK] Correct: Calling a Func delegate is just like calling a normal method once per item, so it does not change how the total time grows with input size.

Interview Connect

Understanding how delegates like Func affect performance helps you explain your code choices clearly and shows you know how code runs as data grows.

Self-Check

"What if the Func delegate called another function inside a loop? How would the time complexity change?"