Reading attributes with reflection in C Sharp (C#) - Time & Space Complexity
When we read attributes using reflection in C#, we want to know how the time it takes changes as the number of attributes or classes grows.
We ask: How does the work increase when we check more attributes or types?
Analyze the time complexity of the following code snippet.
[AttributeUsage(AttributeTargets.Class)]
public class MyAttribute : Attribute { }
public class Example {
public void CheckAttributes(Type[] types) {
foreach (var type in types) {
var attrs = type.GetCustomAttributes(typeof(MyAttribute), false);
// process attrs
}
}
}
This code checks each type in an array to find if it has a specific attribute applied.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each type and calling
GetCustomAttributesto read attributes. - How many times: Once for each type in the input array.
As the number of types increases, the time to check all attributes grows roughly in direct proportion.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 attribute checks |
| 100 | About 100 attribute checks |
| 1000 | About 1000 attribute checks |
Pattern observation: Doubling the number of types roughly doubles the work done.
Time Complexity: O(n)
This means the time to read attributes grows linearly with the number of types checked.
[X] Wrong: "Reading attributes is instant and does not depend on how many types we check."
[OK] Correct: Each type requires a separate check, so more types mean more work and more time.
Understanding how reflection scales helps you write efficient code and answer questions about performance in real projects.
"What if we cached the attributes after the first read? How would the time complexity change when checking many types repeatedly?"