reborn programmer
reborn programmer

Reputation: 514

Using reflection to order properties is slow

I'm using this solution to create an OrderAttribute to order my properties. The output is what I expect, but now that I have profiled the code, I am realizing that GetCustomAttributes is being called way more times than I would like. What would be the best way for me to optimize this for performance?

var ordFunc = new Func<System.Reflection.PropertyInfo, int>(p => ((OrderAttribute) p.GetCustomAttributes(typeof (OrderAttribute), false)[0]).Order);
foreach (var obj in objects)
{
    fileWriter.WriteLine(String.Join(",", obj.GetType().GetProperties().OrderBy(ordFunc).Select(x => x.GetValue(obj).ToString())));
}

Upvotes: 0

Views: 199

Answers (1)

Pavel Pykhtin
Pavel Pykhtin

Reputation: 353

Regarding to Sergey's tip.

var ordFunc = new Func<System.Reflection.PropertyInfo, int>(p => ((OrderAttribute) p.GetCustomAttributes(typeof (OrderAttribute), false)[0]).Order);

if(!objects.Any())
    return;

var properties = objects.First().GetType().GetProperties()
    .OrderBy(ordFunc)
    .ToArray();

foreach (var obj in objects)
{
    fileWriter.WriteLine(String.Join(",", properties.Select(x => x.GetValue(obj).ToString())));
}

Upvotes: 3

Related Questions