vendredi 29 novembre 2019

How big is the impact of accessing directly a property vs accessing a property through reflection?

Suppose you have a class like the following:

public class Test
{
    public string prop {get;set;}
    public string prop2 {get;set;}
    public string prop3 {get;set;}
    public string prop4 {get;set;}
    public string prop5 {get;set;}
    public string prop6 {get;set;}
    public string prop7 {get;set;}
    public string prop8 {get;set;}
    public string prop9 {get;set;}
    public string prop10 {get;set;}
    public string prop11 {get;set;}
    public string prop12 {get;set;}
    public int count{get;set;}
}

I'm writing a method that need to takes at some points only 2-4 properties out of this class and then do some operation (which will be always the same, no matter which property is chosen). To avoid to basically copy/paste the same exact code multiple time (i.e. repeat the //do stuff section, for every switch case), i've written something like this:

    public static DataTable GetTop(currenctCondition)
    {
        DataTable res = null;
        List<Test> appo = GetAllTests();
        string[] propToGet = null;
        switch (currenctCondition)
        {
            case condition1:
                propToGet = new string[] { "prop1", "prop2" };
                break;
            case condition2:
                propToGet = new string[] { "prop3", "prop4" };
                break;
            case condition3:
                propToGet = new string[] { "prop5", "prop6" };
                break;
            case condition4:
                propToGet = new string[] { "prop7", "prop8", "prop9", "prop10" };
                break;
        }
        foreach(Test c in appo)
        {
            foreach(string prop in propToGet)
            {
                string ent = c.GetType().GetProperty(prop).GetGetMethod().Invoke(c, null).ToString();
                // do stuff
            }

        }
        return res;
    }

basically, to make the code more readable and easy to maintein, i build an array of strings that contains the name of the property i have to access, and use the reflection to get the property value using :

string ent = c.GetType().GetProperty(prop).GetGetMethod().Invoke(c, null).ToString();

Of course this is slower than accessing directly the property i need, but i wonder how big can be the impact of this choice. Consider that List<Test> appo can be super small but also very very big ranging from 0 to (possibly, in very rare cases) millions of element.

To get appo i need to do query on MySQL, so my theory is that this operation will always be more time consuming, making the performance loss using the reflection meaningless. I am try to test this, but the setup will cost me some time, so i would like to have some preliminary info from someone who has more experience than me in this field





Aucun commentaire:

Enregistrer un commentaire