Autofac:使用DynamicProxy时提高性能的提示?

时间:2011-03-10 07:27:52

标签: performance autofac castle-dynamicproxy dynamic-proxy

我今天才开始使用DynamicProxy2。并且发现它导致了显着的性能下降。

请参阅下面的代码。 Test1比Test2慢10倍。

使用DynamicProxy时提高性能的任何提示?

class Program
{
    public void Main()
    {
        for (int i = 0; i < 3; i++)
        {
            var stopWatch = Stopwatch.StartNew();
            int count = 1 * 1000 * 1000;

            Test1(count);
            //Test2(count);

            long t = stopWatch.ElapsedMilliseconds;
            Console.WriteLine(t.ToString() + " milliseconds");
            Console.WriteLine(((double)count/(t/1000)).ToString() + " records/1 seconds");
        }
    }

    void Test1(int count)
    {
        var builder = new ContainerBuilder();
        builder.RegisterType<TestViewModel>()
            .EnableClassInterceptors()
            .InterceptedBy(typeof(NotifyPropertyChangedInterceptor));
        builder.RegisterType<NotifyPropertyChangedInterceptor>();

        var container = builder.Build();
        for (int i = 0; i < count; i++)
        {
            container.Resolve<TestViewModel>();
        }
    }

    void Test2(int count)
    {
        var builder = new ContainerBuilder();
        builder.RegisterType<TestViewModel>();

        var container = builder.Build();
        for (int i = 0; i < count; i++)
        {
            container.Resolve<TestViewModel>();
        }
    }
}

public class TestViewModel : INotifyPropertyChanged
{
    [Notify]
    public virtual string Value { get; set; }
    public event PropertyChangedEventHandler PropertyChanged;
}

/// <summary>
/// Copied from: http://serialseb.blogspot.com/2008/05/implementing-inotifypropertychanged.html
/// </summary>
public class NotifyPropertyChangedInterceptor : IInterceptor
{
    public void Intercept(IInvocation invocation)
    {
        // let the original call go through first, so we can notify *after*
        invocation.Proceed();
        if (invocation.Method.Name.StartsWith("set_"))
        {
            string propertyName = invocation.Method.Name.Substring(4);
            var pi = invocation.TargetType.GetProperty(propertyName);

            // check that we have the attribute defined
            if (Attribute.GetCustomAttribute(pi, typeof(NotifyAttribute)) == null)
                return;

            // get the field storing the delegate list that are stored by the event.
            FieldInfo info = invocation.TargetType.GetFields(BindingFlags.Instance | BindingFlags.NonPublic)
                .Where(f => f.FieldType == typeof(PropertyChangedEventHandler))
                .FirstOrDefault();

            if (info != null)
            {
                // get the value of the field
                PropertyChangedEventHandler evHandler = info.GetValue(invocation.InvocationTarget) as PropertyChangedEventHandler;
                // invoke the delegate if it's not null (aka empty)
                if (evHandler != null)
                    evHandler.Invoke(invocation.TargetType, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}

更新

在我的机器上,Test1大约需要45秒,Test2需要大约4.5秒。在阅读Krzysztof Koźmic的答案之后,我尝试将 NotifyPropertyChangedInterceptor 放入单例范围:

builder.RegisterType<NotifyPropertyChangedInterceptor>().SingleInstance();

这让我节省了大约4秒钟。现在Test1大约需要41秒。

更新2:

Test3在我的机器上大约需要8.3秒。因此,似乎单独使用Autofac或DynamicProxy性能不是一个非常大的问题(在我的项目中),但将它们组合在一起会导致性能下降。

    public void Test3(int count)
    {
        var generator = new Castle.DynamicProxy.ProxyGenerator();
        for (int i = 0; i < count; i++)
        {
            generator.CreateClassProxy(typeof(TestViewModel), 
                new NotifyPropertyChangedInterceptor());
        }
    }

2 个答案:

答案 0 :(得分:0)

你得到了什么样的数字?现实生活中的表现是否明显下降?

我不熟悉Autofac如何在内部使用DP,但您不应该注意到性能影响很大。

容器必须做更多的工作来代理VM,实例化拦截器(所以你创建两个对象而不是一个)并将拦截器附加到代理。

如果正确使用缓存,当DP实际生成代理类型时,您将获得一次性能。然后应该重用该类型。

您可以通过检查返回的最后一个代理的类型来轻松检查。

如果它是Castle.Proxies.TestViewModelProxy,则表示缓存正常。

如果是Castle.Proxies.TestViewModelProxy_1000000,则每次都会生成新的代理类型,这可以理解地降低您的效果。

一般来说,性能影响应该可以通过现实生活标准来忽略。

答案 1 :(得分:0)

不是答案,但我想加上我的意见。

我尝试设置容器来手动构建代理,而不是使用AutofacContrib.DynamicProxy2扩展,因此Test1看起来像:

    void Test1(int count)
    {
        var builder = new ContainerBuilder();

        ProxyGenerator pg = new ProxyGenerator();
        builder.Register(c => 
        {
            var obj = pg.CreateClassProxyWithTarget(new TestViewModel(), c.Resolve < NotifyPropertyChangedInterceptor>());
            return (TestViewModel)obj;
        });
        builder.RegisterType<NotifyPropertyChangedInterceptor>().SingleInstance();


        var container = builder.Build();
        for (int i = 0; i < count; i++)
        {
            container.Resolve<TestViewModel>();
        }
    }

这似乎在我的机器上运行大约13.5秒(作为参考,我的原始测试也需要大约45秒)。

我想知道,正如Krzysztof建议的那样,AutofacContrib.DynamicProxy2是否正在做一些天真的事情,比如每次尝试创建一个新的ProxyGenerator。但是当我尝试手动模拟这个时,我得到了一个OOM异常(但是我在这台机器上只有2个演出)。

相关问题