首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> 關於.NET

利用 LINQ Expression 實現屬性高速訪問:反射替代方案效能對比

     編輯:關於.NET

核心思想

將對象放入單元素數組,用 Select 投影屬性,Expression.Lambda 動態編譯委託,緩存複用。比反射快 10 倍+,比直接訪問慢但可動態。

完整實現

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Diagnostics;

public class QuickAccess
{
    static readonly Dictionary _cache = new Dictionary();
    static readonly T[] _single = new T[1];

    public static P GetPropertyValue

(T obj, string propertyName) { _single[0] = obj; int key = propertyName.GetHashCode(); if (!_cache.TryGetValue(key, out Delegate func)) { // 動態構建:param => param.PropertyName ParameterExpression param = Expression.Parameter(typeof(T), "param"); MemberExpression body = Expression.Property(param, propertyName); LambdaExpression lambda = Expression.Lambda(body, param); func = lambda.Compile(); _cache[key] = func; } return _single.Select((Func)func).First(); } } // 使用示例 class User { public string Name { get; set; } public int Age { get; set; } } var user = new User { Name = "Lucifer", Age = 26 }; var sw = Stopwatch.StartNew(); for (int i = 0; i < 10_000_000; i++) int val = QuickAccess.GetPropertyValue(user, "Age"); sw.Stop(); Console.WriteLine($"Elapsed: {sw.ElapsedMilliseconds} ms");

效能對比 (10M 次調用)

適用場景與限制

  • ✅ 動態屬性名(配置驅動、序列化、映射)
  • ✅ 高頻調用同屬性(緩存生效)
  • ❌ 低頻/一次性訪問(編譯開銷不划算)
  • ❌ 結構體/唯讀屬性/索引器(需擴展 Expression 支援)

現代替代:.NET Core 3.0+ Source Generators

編譯期生成強類型訪問器,零反射、零 Expression、零緩存,性能等同直接訪問。推薦用於新專案。

總結

Expression 編譯委託是「反射性能與動態性之間的最佳平衡點」。掌握 Expression.Property → Lambda → Compile → Cache 模式,能在動態場景下獲得接近靜態的性能。但新專案優先考慮 Source Generators 獲得極致效能與類型安全。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
方式耗時相對性能
直接訪問 user.Age~30 ms1.0x (基準)
Expression 快取~120 ms4x 慢
反射 PropertyInfo.GetValue~1500 ms50x 慢
動態 dynamic~800 ms27x 慢