MethodInfo.Invoke performance issue

前端 未结 3 2022
-上瘾入骨i
-上瘾入骨i 2020-12-06 00:19

I am reading and writing data to and from a file. The data in the file can be floats, doubles, ints etc. The type is not known until runtime. I will refer to data type store

3条回答
  •  天涯浪人
    2020-12-06 01:10

    Profile to find the solution that matches your expectations :

    .Net Framework offers plenty of methods to invoke dynamically methods. However they don't perform equally in terms of performance and they are not equally easy to use.

    CreateDelegate may be what you're looking for

    In the recent versions of .Net Framework, CreateDelegate beat by a factor 50 the MethodInfo invoke:

    // The following should be done once since this does some reflection
    var method = typeof (...).GetMethod("ReadGeneric");
    // Here we create a Func that targets the instance of type which has the 
    // ReadGeneric method
    var func = (Func)_method.CreateDelegate(typeof(Func), target);
    
    // Func will be 50x faster than MethodInfo.Invoke
    // use func as a standard Func like 
    // var tout = func(index);
    

    Check this post of mine to see benchmark on different method invocations

提交回复
热议问题