Hello,
I am trying to create custom DynamicObject because I need to be able to access private and internal members of some objects and it is not possible to access private members with default dynamic keyword assignment. The problem I have is terrible performance of my DynamicObject. While 10k loops on default dynamic run in about 50s, on my custom type it runs in about 1600ms.
Here is the code. The type TypeCache is not included, but it contains delegates used to read from or set member of the underlying object of my DynamicObject.
public class PrivateDynamicObject : DynamicObject, IEquatable<PrivateDynamicObject> { private readonly object _value; private readonly Type _type; private readonly TypeCache _cache; public PrivateDynamicObject(object value) { _value = value; _type = value.GetType(); _cache = TypeCache.GetCache(_type); } public override bool TryGetMember(GetMemberBinder binder, out object result) { Func<object, object> d; if (_cache.Getters.TryGetValue(binder.Name, out d)) { result = d(_value); return true; } result = null; return false; } public override bool TrySetMember(SetMemberBinder binder, object value) { Action<object, object> d; if (_cache.Setters.TryGetValue(binder.Name, out d)) { d(_value, value); return true; } return false; } public bool Equals(PrivateDynamicObject other) { return other != null && _value.Equals(other._value); } public override bool Equals(object obj) { return _value.Equals(obj); } public override int GetHashCode() { return _value.GetHashCode(); } public override string ToString() { return _value.ToString(); } }
The slowness comes from reading and setting the properties, instantiating the object is acceptable.
Delegates used to set and get values are compiled using expression trees only once per type.
Thanks