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())));
}
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())));
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.