大数据量下DataTable To List效率对比

时间:2024-01-19 15:44:11

使用反射和动态生成代码两种方式(Reflect和Emit)

反射将DataTable转为List方法

 public static List<T> ToListByReflect<T>(this DataTable dt) where T : new()
{
List<T> ts = new List<T>();
string tempName = string.Empty;
T t = new T();
PropertyInfo[] propertys = t.GetType().GetProperties();
foreach (DataRow dr in dt.Rows)
{
foreach (PropertyInfo pi in propertys)
{
tempName = pi.Name;
if (dt.Columns.Contains(tempName))
{
object value = dr[tempName];
if (value != DBNull.Value)
{
pi.SetValue(t, value, null);
}
}
}
ts.Add(t);
}
return ts;
}

动态生成代码将DataTable转为List方法

 public static List<T> ToListByEmit<T>(this DataTable dt) where T : class, new()
{
List<T> list = new List<T>();
if (dt == null || dt.Rows.Count == )
return list;
DataTableEntityBuilder<T> eblist = DataTableEntityBuilder<T>.CreateBuilder(dt.Rows[]);
foreach (DataRow info in dt.Rows)
list.Add(eblist.Build(info));
dt.Dispose();
dt = null;
return list;
}
public class DataTableEntityBuilder<Entity>
{
private static readonly MethodInfo getValueMethod = typeof(DataRow).GetMethod("get_Item", new Type[] { typeof(int) });
private static readonly MethodInfo isDBNullMethod = typeof(DataRow).GetMethod("IsNull", new Type[] { typeof(int) });
private delegate Entity Load(DataRow dataRecord);
private Load handler;
private DataTableEntityBuilder() { }
public Entity Build(DataRow dataRecord)
{
return handler(dataRecord);
}
public static DataTableEntityBuilder<Entity> CreateBuilder(DataRow dataRecord)
{
DataTableEntityBuilder<Entity> dynamicBuilder = new DataTableEntityBuilder<Entity>();
DynamicMethod method = new DynamicMethod("DynamicCreateEntity", typeof(Entity), new Type[] { typeof(DataRow) }, typeof(Entity), true);
ILGenerator generator = method.GetILGenerator();
LocalBuilder result = generator.DeclareLocal(typeof(Entity));
generator.Emit(OpCodes.Newobj, typeof(Entity).GetConstructor(Type.EmptyTypes));
generator.Emit(OpCodes.Stloc, result);
for (int i = ; i < dataRecord.ItemArray.Length; i++)
{
PropertyInfo propertyInfo = typeof(Entity).GetProperty(dataRecord.Table.Columns[i].ColumnName);
Label endIfLabel = generator.DefineLabel();
if (propertyInfo != null && propertyInfo.GetSetMethod() != null)
{
generator.Emit(OpCodes.Ldarg_0);
generator.Emit(OpCodes.Ldc_I4, i);
generator.Emit(OpCodes.Callvirt, isDBNullMethod);
generator.Emit(OpCodes.Brtrue, endIfLabel);
generator.Emit(OpCodes.Ldloc, result);
generator.Emit(OpCodes.Ldarg_0);
generator.Emit(OpCodes.Ldc_I4, i);
generator.Emit(OpCodes.Callvirt, getValueMethod);
generator.Emit(OpCodes.Unbox_Any, propertyInfo.PropertyType);
generator.Emit(OpCodes.Callvirt, propertyInfo.GetSetMethod());
generator.MarkLabel(endIfLabel);
}
}
generator.Emit(OpCodes.Ldloc, result);
generator.Emit(OpCodes.Ret);
dynamicBuilder.handler = (Load)method.CreateDelegate(typeof(Load));
return dynamicBuilder;
}
}

然后写个控制台程序,对比一下两个方法的效率(测试类大概有40个属性)

大数据量下DataTable To List效率对比

电脑比较渣,使用Emit方法转换100w条数据大概需要7秒,而反射则需要37秒。还测试了当数据量比较小时,Reflect反而比较快。