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

Extension methods for built-in types in C Sharp (C#) - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Extension methods for built-in types
O(n)
Understanding Time Complexity

When we add new functions to built-in types using extension methods, it is important to know how fast these methods run.

We want to see how the time to run the method changes as the input size grows.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


public static class StringExtensions
{
    public static int CountVowels(this string str)
    {
        int count = 0;
        foreach (char c in str)
        {
            if ("aeiouAEIOU".Contains(c)) count++;
        }
        return count;
    }
}
    

This code adds a method to count vowels in any string by checking each character.

Identify Repeating Operations
  • Primary operation: Looping through each character in the string.
  • How many times: Once for every character in the input string.
How Execution Grows With Input

As the string gets longer, the method checks more characters one by one.

Input Size (n)Approx. Operations
10About 10 checks
100About 100 checks
1000About 1000 checks

Pattern observation: The work grows directly with the length of the string.

Final Time Complexity

Time Complexity: O(n)

This means the time to count vowels grows in a straight line as the string gets longer.

Common Mistake

[X] Wrong: "Extension methods always add extra hidden loops making them slow."

[OK] Correct: Extension methods run like normal methods; their speed depends on what code they contain, not on being extensions.

Interview Connect

Understanding how extension methods perform helps you write clean code without worrying about hidden slowdowns.

Self-Check

"What if we changed the method to count vowels only in the first half of the string? How would the time complexity change?"