Custom attribute classes in C Sharp (C#) - Time & Space Complexity
When we use custom attribute classes in C#, it's important to understand how the program's work grows as we apply these attributes to many parts of the code.
We want to know how the time to check or use these attributes changes when the number of classes or methods with attributes increases.
Analyze the time complexity of the following code snippet.
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class MyCustomAttribute : Attribute
{
public string Info { get; }
public MyCustomAttribute(string info) => Info = info;
}
public class Example
{
[MyCustomAttribute("Test")]
public void Method() { }
}
// Later, reflection is used to find attributes:
var methods = typeof(Example).GetMethods();
foreach (var method in methods)
{
var attrs = method.GetCustomAttributes(typeof(MyCustomAttribute), false);
// process attrs
}
This code defines a custom attribute and then uses reflection to find all methods with that attribute.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through all methods of a class to check for custom attributes.
- How many times: Once for each method in the class.
As the number of methods increases, the program checks each method one by one for the attribute.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 attribute checks |
| 100 | About 100 attribute checks |
| 1000 | About 1000 attribute checks |
Pattern observation: The work grows directly with the number of methods; doubling methods doubles the checks.
Time Complexity: O(n)
This means the time to find attributes grows in a straight line with the number of methods checked.
[X] Wrong: "Checking attributes is instant and does not depend on how many methods exist."
[OK] Correct: Each method must be checked one by one, so more methods mean more work.
Understanding how attribute checks scale helps you write efficient code and reason about reflection performance in real projects.
What if we cached the attributes after the first check? How would the time complexity change when accessing attributes multiple times?