gpt4 book ai didi

c# - 需要比反射(reflection)更好的方法

转载 作者:太空狗 更新时间:2023-10-29 22:56:02 24 4
gpt4 key购买 nike

我正在读取一个 CSV 文件,记录被记录为一个字符串 []。我想获取每条记录并将其转换为自定义对象。

T GetMyObject<T>();

目前我是通过反射来做这件事的,这真的很慢。我正在测试一个包含数百万条记录的 515 Meg 文件。解析时间不到 10 秒。使用 Convert.ToSomeType 的手动转换创建自定义对象需要不到 20 秒的时间。但通过反射转换为对象大约需要 4 分钟。

自动处理此问题的好方法是什么?

似乎很多时间花在了PropertyInfo.SetValue上方法。我尝试缓存属性 MethodInfo setter 并改用它,但实际上速度较慢。

我也试过将它转换成委托(delegate),就像伟大的 Jon Skeet 在这里建议的那样:Improving performance reflection , what alternatives should I consider ,但问题是我不知道属性类型是什么。我能够得到委托(delegate)

var myObject = Activator.CreateInstance<T>();
foreach( var property in typeof( T ).GetProperties() )
{
var d = Delegate.CreateDelegate( typeof( Action<,> )
.MakeGenericType( typeof( T ), property.PropertyType ), property.GetSetMethod() );
}

这里的问题是我无法将委托(delegate)转换为具体类型,如 Action<T, int> ,因为 int 的属性类型事先不知道。

最佳答案

我要说的第一件事是手动编写一些示例代码,告诉您可以预期的绝对最佳情况是什么 - 看看您当前的代码是否值得修复。

如果您正在使用 PropertyInfo.SetValue 等,那么您绝对可以让它更快,即使使用 juts object - HyperDescriptor 可能是一个好的开始(它比原始反射快显着,但没有制作代码更复杂)。

为了获得最佳性能,动态 IL 方法是可行的方法(预编译一次);在 2.0/3.0 中,也许是 DynamicMethod ,但在 3.5 中我更喜欢 Expression (与 Compile() )。如果您需要更多详细信息,请告诉我?


使用 Expression CsvReader 的实现,使用列标题提供映射(它按照相同的方式发明了一些数据);它使用 IEnumerable<T> 作为返回类型以避免缓冲数据(因为你似乎有很多数据):

using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using LumenWorks.Framework.IO.Csv;
class Entity
{
public string Name { get; set; }
public DateTime DateOfBirth { get; set; }
public int Id { get; set; }

}
static class Program {

static void Main()
{
string path = "data.csv";
InventData(path);

int count = 0;
foreach (Entity obj in Read<Entity>(path))
{
count++;
}
Console.WriteLine(count);
}
static IEnumerable<T> Read<T>(string path)
where T : class, new()
{
using (TextReader source = File.OpenText(path))
using (CsvReader reader = new CsvReader(source,true,delimiter)) {

string[] headers = reader.GetFieldHeaders();
Type type = typeof(T);
List<MemberBinding> bindings = new List<MemberBinding>();
ParameterExpression param = Expression.Parameter(typeof(CsvReader), "row");
MethodInfo method = typeof(CsvReader).GetProperty("Item",new [] {typeof(int)}).GetGetMethod();
Expression invariantCulture = Expression.Constant(
CultureInfo.InvariantCulture, typeof(IFormatProvider));
for(int i = 0 ; i < headers.Length ; i++) {
MemberInfo member = type.GetMember(headers[i]).Single();
Type finalType;
switch (member.MemberType)
{
case MemberTypes.Field: finalType = ((FieldInfo)member).FieldType; break;
case MemberTypes.Property: finalType = ((PropertyInfo)member).PropertyType; break;
default: throw new NotSupportedException();
}
Expression val = Expression.Call(
param, method, Expression.Constant(i, typeof(int)));
if (finalType != typeof(string))
{
val = Expression.Call(
finalType, "Parse", null, val, invariantCulture);
}
bindings.Add(Expression.Bind(member, val));
}

Expression body = Expression.MemberInit(
Expression.New(type), bindings);

Func<CsvReader, T> func = Expression.Lambda<Func<CsvReader, T>>(body, param).Compile();
while (reader.ReadNextRecord()) {
yield return func(reader);
}
}
}
const char delimiter = '\t';
static void InventData(string path)
{
Random rand = new Random(123456);
using (TextWriter dest = File.CreateText(path))
{
dest.WriteLine("Id" + delimiter + "DateOfBirth" + delimiter + "Name");
for (int i = 0; i < 10000; i++)
{
dest.Write(rand.Next(5000000));
dest.Write(delimiter);
dest.Write(new DateTime(
rand.Next(1960, 2010),
rand.Next(1, 13),
rand.Next(1, 28)).ToString(CultureInfo.InvariantCulture));
dest.Write(delimiter);
dest.Write("Fred");
dest.WriteLine();
}
dest.Close();
}
}
}

使用 TypeConverter 而不是 Parse 的第二个版本(见评论):

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using LumenWorks.Framework.IO.Csv;
class Entity
{
public string Name { get; set; }
public DateTime DateOfBirth { get; set; }
public int Id { get; set; }

}
static class Program
{

static void Main()
{
string path = "data.csv";
InventData(path);

int count = 0;
foreach (Entity obj in Read<Entity>(path))
{
count++;
}
Console.WriteLine(count);
}
static IEnumerable<T> Read<T>(string path)
where T : class, new()
{
using (TextReader source = File.OpenText(path))
using (CsvReader reader = new CsvReader(source, true, delimiter))
{

string[] headers = reader.GetFieldHeaders();
Type type = typeof(T);
List<MemberBinding> bindings = new List<MemberBinding>();
ParameterExpression param = Expression.Parameter(typeof(CsvReader), "row");
MethodInfo method = typeof(CsvReader).GetProperty("Item", new[] { typeof(int) }).GetGetMethod();

var converters = new Dictionary<Type, ConstantExpression>();
for (int i = 0; i < headers.Length; i++)
{
MemberInfo member = type.GetMember(headers[i]).Single();
Type finalType;
switch (member.MemberType)
{
case MemberTypes.Field: finalType = ((FieldInfo)member).FieldType; break;
case MemberTypes.Property: finalType = ((PropertyInfo)member).PropertyType; break;
default: throw new NotSupportedException();
}
Expression val = Expression.Call(
param, method, Expression.Constant(i, typeof(int)));
if (finalType != typeof(string))
{
ConstantExpression converter;
if (!converters.TryGetValue(finalType, out converter))
{
converter = Expression.Constant(TypeDescriptor.GetConverter(finalType));
converters.Add(finalType, converter);
}
val = Expression.Convert(Expression.Call(converter, "ConvertFromInvariantString", null, val),
finalType);
}
bindings.Add(Expression.Bind(member, val));
}

Expression body = Expression.MemberInit(
Expression.New(type), bindings);

Func<CsvReader, T> func = Expression.Lambda<Func<CsvReader, T>>(body, param).Compile();
while (reader.ReadNextRecord())
{
yield return func(reader);
}
}
}
const char delimiter = '\t';
static void InventData(string path)
{
Random rand = new Random(123456);
using (TextWriter dest = File.CreateText(path))
{
dest.WriteLine("Id" + delimiter + "DateOfBirth" + delimiter + "Name");
for (int i = 0; i < 10000; i++)
{
dest.Write(rand.Next(5000000));
dest.Write(delimiter);
dest.Write(new DateTime(
rand.Next(1960, 2010),
rand.Next(1, 13),
rand.Next(1, 28)).ToString(CultureInfo.InvariantCulture));
dest.Write(delimiter);
dest.Write("Fred");
dest.WriteLine();
}
dest.Close();
}
}
}

关于c# - 需要比反射(reflection)更好的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2044371/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com