2014-12-04 2 views
0

this solution을 사용하여 내 속성을 주문하는 데 OrderAttribute를 만듭니다. 결과물은 예상대로이지만 코드를 프로파일 링 했으므로 GetCustomAttributes가 내가 원하는 것보다 더 많이 호출되고 있음을 알게되었습니다. 성능 최적화를위한 가장 좋은 방법은 무엇입니까?리플렉션을 사용하여 속성을 주문하는 것이 느립니다.

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()))); 
} 
+2

정적 목록에 속성 및 속성 정보를 캐시하면 훨씬 빠르게 작동합니다. –

답변

3

세르게이의 팁에 관해서.

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()))); 
} 
관련 문제