Extension methods for built-in types in C Sharp (C#) - Time & Space 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.
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.
- Primary operation: Looping through each character in the string.
- How many times: Once for every character in the input string.
As the string gets longer, the method checks more characters one by one.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks |
| 100 | About 100 checks |
| 1000 | About 1000 checks |
Pattern observation: The work grows directly with the length of the string.
Time Complexity: O(n)
This means the time to count vowels grows in a straight line as the string gets longer.
[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.
Understanding how extension methods perform helps you write clean code without worrying about hidden slowdowns.
"What if we changed the method to count vowels only in the first half of the string? How would the time complexity change?"