最近做了一个.Net Core环境下,基于NPOI的Excel导入导出以及Word操作的服务封装,
涉及到大量反射操作,在性能优化过程中使用到了表达式树,记录一下。

Excel导入是相对比较麻烦的一块,实现的效果是:调用方只需要定义一个类,只需要标记特性,
服务读取Excel=>校验(正则、必填、整数范围、日期、数据库是否存在、数据重复) =>将校验结果返回 => 提供方法将Excel数据
转换为指定类集合。

在最后一步转换,最开始用反射实现,性能较差;后来通过了反射+委托,表达式树方式进行优化,
最终性能接近了硬编码。见图,转换近5000条有效数据,耗时仅100毫秒不到,是反射的近20倍。

读取Excel数据之后,我将数据读取到了自定义的两个类(方便后面的校验)

   public class ExcelDataRow
{
/// <summary>
/// 行号
/// </summary>
public int RowIndex { get; set; } /// <summary>
/// 单元格数据
/// </summary>
public List<ExcelDataCol> DataCols { get; set; } = new List<ExcelDataCol>(); /// <summary>
/// 是否有效
/// </summary>
public bool IsValid { get; set; } /// <summary>
/// 错误信息
/// </summary>
public string ErrorMsg { get; set; }
} public class ExcelDataCol : ExcelCol
{
/// <summary>
/// 对应属性名称
/// </summary>
public string PropertyName { get; set; } /// <summary>
/// 行号
/// </summary>
public int RowIndex { get; set; } /// <summary>
/// 字符串值
/// </summary>
public string ColValue { get; set; }
}

校验完之后,需要将ExcelDataRow转换为指定类型

using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Threading.Tasks; namespace Ade.OfficeService.Excel
{
/// <summary>
/// 生成表达式目录树 缓存
/// </summary>
public class ExpressionMapper
{
private static Hashtable Table = Hashtable.Synchronized(new Hashtable(1024)); /// <summary>
/// 将ExcelDataRow快速转换为指定类型
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dataRow"></param>
/// <returns></returns>
public static T FastConvert<T>(ExcelDataRow dataRow)
{
//利用表达式树,动态生成委托并缓存,得到接近于硬编码的性能
//最终生成的代码近似于(假设T为Person类)
//Func<ExcelDataRow,Person>
// new Person(){
// Name = Convert(ChangeType(dataRow.DataCols.SingleOrDefault(c=>c.PropertyName == prop.Name).ColValue,prop.PropertyType),prop.ProertyType),
// Age = Convert(ChangeType(dataRow.DataCols.SingleOrDefault(c=>c.PropertyName == prop.Name).ColValue,prop.PropertyType),prop.ProertyType)
// }
// } string propertyNames = string.Empty;
dataRow.DataCols.ForEach(c => propertyNames += c.PropertyName + "_");
var key = typeof(T).FullName + "_" + propertyNames.Trim('_'); if (!Table.ContainsKey(key))
{
List<MemberBinding> memberBindingList = new List<MemberBinding>(); MethodInfo singleOrDefaultMethod = typeof(Enumerable)
.GetMethods()
.Single(m => m.Name == "SingleOrDefault" && m.GetParameters().Count() == 2)
.MakeGenericMethod(new[] { typeof(ExcelDataCol) }); foreach (var prop in typeof(T).GetProperties())
{
Expression<Func<ExcelDataCol, bool>> lambdaExpr = c => c.PropertyName == prop.Name; MethodInfo changeTypeMethod = typeof(ExpressionMapper).GetMethods().Where(m => m.Name == "ChangeType").First(); Expression expr =
Expression.Convert(
Expression.Call(changeTypeMethod
, Expression.Property(
Expression.Call(
singleOrDefaultMethod
, Expression.Constant(dataRow.DataCols)
, lambdaExpr)
, typeof(ExcelDataCol), "ColValue"), Expression.Constant(prop.PropertyType))
, prop.PropertyType); memberBindingList.Add(Expression.Bind(prop, expr));
} MemberInitExpression memberInitExpression = Expression.MemberInit(Expression.New(typeof(T)), memberBindingList.ToArray());
Expression<Func<ExcelDataRow, T>> lambda = Expression.Lambda<Func<ExcelDataRow, T>>(memberInitExpression, new ParameterExpression[]
{
Expression.Parameter(typeof(ExcelDataRow), "p")
}); Func<ExcelDataRow, T> func = lambda.Compile();//拼装是一次性的
Table[key] = func;
}
var ss = (Func<ExcelDataRow, T>)Table[key]; return ((Func<ExcelDataRow, T>)Table[key]).Invoke(dataRow);
} public static object ChangeType(string stringValue, Type type)
{
object obj = null; Type nullableType = Nullable.GetUnderlyingType(type);
if (nullableType != null)
{
if (stringValue == null)
{
obj = null;
} }
else if (typeof(System.Enum).IsAssignableFrom(type))
{
obj = Enum.Parse(type, stringValue);
}
else
{
obj = Convert.ChangeType(stringValue, type);
} return obj;
}
}
}

  

利用表达式树Expression优化反射性能的更多相关文章

  1. [C#] C# 知识回顾 - 表达式树 Expression Trees

    C# 知识回顾 - 表达式树 Expression Trees 目录 简介 Lambda 表达式创建表达式树 API 创建表达式树 解析表达式树 表达式树的永久性 编译表达式树 执行表达式树 修改表达 ...

  2. 表达式树 Expression

    转载泛型方法动态生成表达式树 Expression public string GetGridJSON(TraderInfo model) { IQueryable<TraderInfo> ...

  3. 表达式树(Expression Tree)

    饮水思源 本文并非原创而是下面网址的一个学习笔记 https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/e ...

  4. C# 知识回顾 - 表达式树 Expression Trees

    C# 知识回顾 - 表达式树 Expression Trees 目录 简介 Lambda 表达式创建表达式树 API 创建表达式树 解析表达式树 表达式树的永久性 编译表达式树 执行表达式树 修改表达 ...

  5. 【C#表达式树 七】 反射在表达式树中的应用 ListInitExpression

    以下都是反射在表达式树中的应用 对象初始化 Expression.MemberInit 反射获取成员(字段 或者属性),绑定数据,然后生成 成员表达式节点 class Animal { public ...

  6. 泛型方法动态生成表达式树 Expression

    public string GetGridJSON(TraderInfo model) { IQueryable<TraderInfo> Temp = db.TraderInfo; if ...

  7. jQuery find() 搜索所有段落中的后代 C# find() 第一个匹配元素 Func 有返回值 Action是没有返回值 Predicate 只有一个参数且返回值为bool 表达式树Expression

    所有p后代span Id为 TotalProject 的 select 标签 的后代 option标签 为选中的 text using System; using System.Collections ...

  8. 表达式树Expression

    Expression表达式树动态查询 在进行数据列表的查询中,我们通常会使用两种方式进行查询: linq查询 数据库sql语句查询 这样固然可以实现查询,本人之前也都是这么做的,因为查询的条件很少.使 ...

  9. C# 表达式树 Expression

    表达式树是定义代码的数据结构. 它们基于编译器用于分析代码和生成已编译输出的相同结构. 几种常见的表达式 BinaryExpression 包含二元运算符的表达式 BinaryExpression b ...

随机推荐

  1. 算法(Algorithms)第4版 练习 1.5.24

    package com.qiusongde; import edu.princeton.cs.algs4.StdOut; public class Exercise1524 { public stat ...

  2. Docker-端口映射与容器互联

    在使用docker过程中,通常会碰到需要多个服务组件容器共同协作的情况,这往往需要多个容器之间有能够互相访问到对方的服务除了通过网络访问外,Docker还提供了两个很方便的功能来满足服务访问的基本需求 ...

  3. 句柄与MFC对象关系和相互获取

    Windows对象是以句柄来标识的,对应的MFC类就是这些句柄的C++包装.内存中的Windows对象一定有唯一的句柄来标识,但不一定有对应的MFC类对象在内存中.当需要获取Windows对象的对应M ...

  4. css sprite技巧详解

    1. [代码][CSS]代码 CSSSprites在国内很多人叫css精灵,是一种网页图片应用处理方式.它允许你将一个页面涉及到的所有零星图片都包含到一张大图中去,这样一来,当访问该页面时,载入的图片 ...

  5. hibernate复习第(4)天

    1.hibernate的映射类型.hbm.xml中property中的type属性.这个type属性是表示持久化类中的属性对应数据库中的什么数据类型,用来构建一种映射type的可选值:hibernat ...

  6. php断点续传

    http://www.cnblogs.com/xproer/archive/2012/10/26/2741264.html

  7. Android Studio & Butter Knife —— 快速开发

    Butter Knife是一个Android的注解框架,可以帮助用户快速完成视图.资源与对象的绑定,完成事件的监听.(也就是少写findViewById()) 具体的介绍可以参考官方主页: http: ...

  8. FFMPEG实现H264的解码(从源代码角度)

    农历2014年底了,将前段时间工作中研究的FFMPEG解码H264流程在此做一下整理,也算作年终技术总结了! H264解码原理: H264的原理参考另一篇博文 http://blog.csdn.net ...

  9. CF221C Circling Round Treasures

    题目大意 给定一个$n\times m$的网格$(n,m\leq 20)$,每个格子都是$S\space \#\space B\space x\space .$中第一个. $S$表示起点,保证有且仅有 ...

  10. 【LeetCode】084. Largest Rectangle in Histogram

    题目: Given n non-negative integers representing the histogram's bar height where the width of each ba ...