Big-O of .GetProperties()

这一生的挚爱 提交于 2019-12-10 15:19:52

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!