How slow is Reflection

后端 未结 7 2027
时光取名叫无心
时光取名叫无心 2020-12-02 07:43

I recently created an interface layer to distinguish the DataAccessProvider from our Business logic layer. With this approach we can change our choice of DataAccessProvider

7条回答
  •  借酒劲吻你
    2020-12-02 07:58

    In most cases: more than fast enough. For example, if you are using this to create a DAL wrapper object, the time taken to create the object via reflection will be minuscule compared to the time it needs to connect to a network. So optimising this would be a waste of time.

    If you are using reflection in a tight loop, there are tricks to improve it:

    • generics (using a wrapper where T : new() and MakeGenericType)
    • Delegate.CreateDelegate (to a typed delegate; doesn't work for constructors)
    • Reflection.Emit - hardcore
    • Expression (like Delegate.CreateDelegate, but more flexible, and works for constructors)

    But for your purposes, CreateInstance is perfectly fine. Stick with that, and keep things simple.


    Edit: while the point about relative performance remains, and while the most important thing, "measure it", remains, I should clarify some of the above. Sometimes... it does matter. Measure first. However, if you find it is too slow, you might want to look at something like FastMember, which does all the Reflection.Emit code quietly in the background, to give you a nice easy API; for example:

    var accessor = TypeAccessor.Create(type);
    List results = new List();
    foreach(var row in rows) {
        object obj = accessor.CreateNew();
        foreach(var col in cols) {
            accessor[obj, col.Name] = col.Value;
        }
        results.Add(obj);
    }
    
    
    

    which is simple, but will be very fast. In the specific example I mention about a DAL wrapper—if you are doing this lots, consider something like dapper, which again does all the Reflection.Emit code in the background to give you the fastest possible but easy to use API:

    int id = 12345;
    var orders = connection.Query(
        "select top 10 * from Orders where CustomerId = @id order by Id desc",
        new { id }).ToList();
    

    提交回复
    热议问题