Can Delegate.DynamicInvoke be avoided in this generic code?

前端 未结 3 1016
醉话见心
醉话见心 2021-02-05 22:27

This question is partly about delegates, and partly about generics.

Given the simplified code:

internal sealed class TypeDispatchProcessor
{
    private          


        
3条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-05 22:51

    I strongly suspect that wrapping the calls would be a lot more efficient than using DynamicInvoke. Your code would then be:

    internal sealed class TypeDispatchProcessor
    {
        private readonly Dictionary> _actionByType 
            = new Dictionary>();
    
        public void RegisterProcedure(Action action)
        {
            _actionByType[typeof(T)] = item => action((T) item);
        }
    
        public void ProcessItem(object item)
        {
            Action action;
            if (_actionByType.TryGetValue(item.GetType(), out action))
            {
                action(item);
            }
        }
    }
    
    
    

    It's worth benchmarking it, but I think you'll find this a lot more efficient. DynamicInvoke has to check all the arguments with reflection etc, instead of the simple cast in the wrapped delegate.

    提交回复
    热议问题