jeudi 27 septembre 2018

Which is faster and/or lighter: GetMethods or GetMethod?

I have an operation that queries for a method via reflection, and this operation executes several times, but always over the same class.

I was wondering if it is lighter to have a static property containing all the methods of the class, and then querying with Linq for the desired method, or keep using GetMethod directly.

Current code, this method gets called within a loop

// Class containing all methods, initialized via constructor   
private readonly MyType _myType; 

private MethodInfo ReturnMethod(string identifier)
{
    var type = _myType.GetType();

    var method = type.GetMethod(identifier, 
     BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);

    if (metodo == null)
        throw new Exception($"Method not found ({identifier}).");

    return method;
}

And this is the new proposed code:

private static MethodInfo[] AllMethods => typeof(MyType).GetMethods(BindingFlags.IgnoreCase 
     | BindingFlags.Public | BindingFlags.Instance);

private MethodInfo ReturnMethod(string identifier)
{
    var method = AllMethods.FirstOrDefault(m => m.Name == identifier);

    if (method == null)
        throw new MacroException($"Method not found ({identifier}).");

    return method;
}

So, first: should I be concerned with speed or CPU/Memory cost regarding this? If yes:

Second: which one is be faster or lighter?

Third: Having all methods in a static property, would be memory expensive?





Aucun commentaire:

Enregistrer un commentaire