Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Big-O of .GetProperties()

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?

like image 485
Travis J Avatar asked Mar 26 '12 19:03

Travis J


2 Answers

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.

like image 133
Henk Holterman Avatar answered Sep 22 '22 00:09

Henk Holterman


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.

like image 36
marcind Avatar answered Sep 21 '22 00:09

marcind