问题
If there are n properties, then is the Big-O of .GetProperties O(n) or are there are processes involved in the reflection that add complexity?
Say there is this defined class:
public class Reflector
{
public string name { get; set; }
public int number { get; set; }
public bool flag { get; set; }
public List<string> etc { get; set; }
}
And then this call is made:
var reflect = new Reflector();
PropertyInfo[] properties = reflect.GetType().GetProperties();
What is the time complexity, i.e. Big-O, of .GetProperties()
? Considering that there are 4 properties, would this only take 4 iterations or is it more complex than that? Or, is it O(1) with some standard set of complexity to get to the list - which seems it must still be O(n) just to build the properties array?
回答1:
Big-O is about asymptotic complexity, in other words O(n) is only relevant for large values of n
.
A class will never have enough properties to make this relevant.
For practical purposes, you might as well consider it O(1), but with a very big constant.
This kind of issue is expressed in nanoseconds, not Big-O notations.
回答2:
More complicated than that. The algorithm has to include the base type chain as well. In addition, the implementation might cache the result, so the ammortized cost might actually be O(1).
But in practice, reflection is always pretty slow, so you should probably profile your application and make changes until you meet your performance goals.
来源:https://stackoverflow.com/questions/9878743/big-o-of-getproperties