我今天才开始使用 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());
}
}