Func delegate type in C Sharp (C#) - Time & Space 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?
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 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.
Each time we add one more number, we call the Func one more time.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 calls to Func |
| 100 | 100 calls to Func |
| 1000 | 1000 calls to Func |
Pattern observation: The number of operations grows directly with the input size.
Time Complexity: O(n)
This means the time to complete the task grows in a straight line as the input size increases.
[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.
Understanding how delegates like Func affect performance helps you explain your code choices clearly and shows you know how code runs as data grows.
"What if the Func delegate called another function inside a loop? How would the time complexity change?"