比較三種序列化物件建立方式的效能:
1. 反射建立 (Activator.CreateInstance + PropertyInfo.SetValue)
2. 動態編譯 (CodeDom / Roslyn)
3. 靜態編譯序列化適配器 (預先生成強型別存取委托)
| 方式 | 耗時 (秒) | 相對效能 |
|---|---|---|
| 靜態編譯序列化 (原生) | ~1.1 | 基準 (1x) |
| 反射序列化 | ~4.2 ~ 7.8 | 4-7x 慢 |
| 動態編譯序列化 | ~4.1 ~ 7.5 | 4-7x 慢 |
| 動態建立適配器 (強型別委托) | ~1.1 | 接近原生 (1x) |
SetValue 晚期繫結呼叫。Action<T, object> 或 Func<object, T> 委托,直接存取屬性,效能提升 **4-7 倍**,接近手寫程式碼。static readonly Dictionary PropertyCache = new();
PropertyInfo[] props = PropertyCache.GetOrAdd(type, t => t.GetProperties());
var setMethod = prop.GetSetMethod();
var setter = (Action
var instance = Expression.Parameter(typeof(object), "instance");
var value = Expression.Parameter(typeof(object), "value");
var castInstance = Expression.Convert(instance, type);
var castValue = Expression.Convert(value, prop.PropertyType);
var call = Expression.Call(castInstance, prop.GetSetMethod(), castValue);
var lambda = Expression.Lambda>(call, instance, value);
var setter = lambda.Compile();
編譯期自動生成強型別序列化邏輯,零反射、零啟動開銷,效能最優。
PropertyInfo.SetValue。