성태의 닷넷 이야기
홈 주인
모아 놓은 자료
프로그래밍
질문/답변
사용자 관리
사용자
메뉴
아티클
외부 아티클
유용한 코드
온라인 기능
MathJax 입력기
최근 덧글
[정성태] Working with Rust Libraries from C#...
[정성태] Detecting blocking calls using asyn...
[정성태] 아쉽게도, 커뮤니티는 아니고 개인 블로그입니다. ^^
[정성태] 질문이 잘 이해가 안 됩니다. 우선, 해당 소스코드에서 ILis...
[양승조
] var대신 dinamic으로 선언해서 해결은 했습니다. 맞는 해...
[양승조
] 또 막혔습니다. ㅠㅠ var list = props[i].Ge...
[양승조
] 아. 감사합니다. 어제는 안됐던것 같은데....정신을 차려야겠네...
[정성태] "props[i].GetValue(props[i])" 코드에서 ...
[정성태] 저렇게 조각 코드 말고, 실제로 재현이 되는 예제 프로젝트를 압...
[정성태] Modules 창(Ctrl+Shift+U)을 띄워서, 해당 Op...
글쓰기
제목
이름
암호
전자우편
HTML
홈페이지
유형
제니퍼 .NET
닷넷
COM 개체 관련
스크립트
VC++
VS.NET IDE
Windows
Team Foundation Server
디버깅 기술
오류 유형
개발 환경 구성
웹
기타
Linux
Java
DDK
Math
Phone
Graphics
사물인터넷
부모글 보이기/감추기
내용
<div style='display: inline'> <h1 style='font-family: Malgun Gothic, Consolas; font-size: 20pt; color: #006699; text-align: center; font-weight: bold'>struct로 정의한 값 형식(Value Type)의 경우 Equals 재정의를 권장합니다.</h1> <p> 다음과 같은 코드를 볼까요!<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > using System; class Program { static void Main(string[] args) { MyStruct ms1 = new MyStruct { _n = 5 }; MyStruct ms2 = new MyStruct { _n = 5 }; Console.WriteLine(<span style='color: blue; font-weight: bold'>ms1.Equals(ms2)</span>); // True } } struct MyStruct { public int _n; } </pre> <br /> 기본적인 System.Object 타입의 Equals 메서드는 .NET Reflector로 살펴보면 RuntimeHelpers.Equals 호출로 연결됩니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries"), __DynamicallyInvokable] public virtual bool Equals(object obj) { return <span style='color: blue; font-weight: bold'>RuntimeHelpers.Equals(this, obj);</span> } [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries"), __DynamicallyInvokable] public static bool Equals(object objA, object objB) { return ((objA == objB) || (((objA != null) && (objB != null)) && objA.Equals(objB))); } </pre> <br /> 하지만, struct로 정의한 C# 타입은 System.Object가 아닌 System.ValueType을 부모 클래스로 지정되기 때문에 그 클래스에 재정의된 Equals 메서드가 실행됩니다. 그 코드가 재미있는데요.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > [SecuritySafeCritical, __DynamicallyInvokable] public override bool Equals(object obj) { if (obj == null) { return false; } RuntimeType type = (RuntimeType) base.GetType(); RuntimeType type2 = (RuntimeType) obj.GetType(); if (type2 != type) { return false; } object a = this; if (CanCompareBits(this)) { return FastEqualsCheck(a, obj); } <span style='color: blue; font-weight: bold'>FieldInfo[] fields = type.GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);</span> for (int i = 0; i < fields.Length; i++) { object obj3 = ((RtFieldInfo) fields[i]).UnsafeGetValue(a); object obj4 = ((RtFieldInfo) fields[i]).UnsafeGetValue(obj); if (obj3 == null) { if (obj4 != null) { return false; } } else if (!obj3.Equals(obj4)) { return false; } } return true; } </pre> <br /> 보는 바와 같이 Reflection을 통해 일일이 값 비교를 하고 있습니다. Reflection이 느리다는 것은 다들 아실텐데요, 따라서 당연히 다음과 같이 Equals 메서드를 재정의해주는 것이 실행 속도가 더 빠릅니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > using System; class Program { static void Main(string[] args) { MyStructWithEquals msw1 = new MyStructWithEquals { _n = 2 }; MyStructWithEquals msw2 = new MyStructWithEquals { _n = 2 }; Console.WriteLine(msw1.Equals(msw2)); // True } } struct MyStruct { public int _n; } struct MyStructWithEquals { public int _n; <span style='color: blue; font-weight: bold'>public override bool Equals(object obj) { MyStructWithEquals target = (MyStructWithEquals)obj; return _n == target._n; } public override int GetHashCode() { return _n.GetHashCode(); }</span> } </pre> <br /> 실제로 성능 비교를 해볼까요? ^^<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > using System; using System.Diagnostics; class Program { static void Main(string[] args) { MyStruct ms1 = new MyStruct { _n = 5 }; MyStruct ms2 = new MyStruct { _n = 5 }; MyStructWithEquals msw1 = new MyStructWithEquals { _n = 2 }; MyStructWithEquals msw2 = new MyStructWithEquals { _n = 2 }; // JIT 컴파일 용 CompareTime1(ms1, ms2, 1); CompareTime2(msw1, msw2, 1); // 성능 측정 CompareTime1(ms1, ms2, 100000); CompareTime2(msw1, msw2, 100000); } private static void CompareTime1(MyStruct ms1, MyStruct ms2, int count) { Stopwatch st = new Stopwatch(); st.Start(); for (int i = 0; i < count; i ++) { ms1.Equals(ms2); } st.Stop(); Console.WriteLine("CompareTime1 - # of " + count + ": " + st.ElapsedTicks); } private static void CompareTime2(MyStructWithEquals msw1, MyStructWithEquals msw2, int count) { Stopwatch st = new Stopwatch(); st.Start(); for (int i = 0; i < count; i++) { msw1.Equals(msw2); } st.Stop(); Console.WriteLine("CompareTime2 - # of " + count + ": " + st.ElapsedTicks); } } struct MyStruct { public int _n; } struct MyStructWithEquals { public int _n; public override bool Equals(object obj) { MyStructWithEquals target = (MyStructWithEquals)obj; return _n == target._n; } public override int GetHashCode() { return _n.GetHashCode(); } } </pre> <br /> 실행해 보면?<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > CompareTime1 - # of 100000: 16895 CompareTime2 - # of 100000: 3165 CompareTime1 - # of 1000000: 108633 CompareTime2 - # of 1000000: 34897 CompareTime1 - # of 10000000: 1108970 CompareTime2 - # of 10000000: 332720 </pre> <br /> 약 3배 이상의 성능 차이가 나는 것을 볼 수 있습니다.<br /> <br /> <hr style='width: 50%' /><br /> <br /> Equals 메서드를 잘 쓰지 않는 듯 해도, 알게 모르게 사용되는 경우가 있습니다. 바로 Dictionary 류의 자료 구조를 사용할 때입니다. 일례로, 다음과 같이 HashSet을 사용하는 경우,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > using System; using System.Collections.Generic; class Program { static void Main(string[] args) { MyStructWithEquals msw1 = new MyStructWithEquals { _n = 2 }; MyStructWithEquals msw2 = new MyStructWithEquals { _n = 2 }; <span style='color: blue; font-weight: bold'>HashSet<MyStructWithEquals> hs2 = new HashSet<MyStructWithEquals>(); hs2.Add(msw1); hs2.Add(msw2);</span> } } struct MyStructWithEquals { public int _n; public override bool Equals(object obj) { MyStructWithEquals target = (MyStructWithEquals)obj; return _n == target._n; } public override int GetHashCode() { return _n.GetHashCode(); } } </pre> <br /> HashSet.Add, MyStructWithEquals.GetHashCode, MyStructWithEquals.Equals 메서드에 BP(Breakpoint)를 걸고 F11 키를 누르면, Add -> GetHashCode -> Equals 순으로 실행이 되는 것을 확인할 수 있습니다. 즉, 여러분들이 Dictionary 류의 자료 구조를 사용한다면 필연적으로 Equals/GetHashCode 메서드가 불리게 되고, 이것을 재정의하지 않았다면 닷넷은 기본 구현체인 Reflection을 이용한 비교 작업을 수행하게 되는 것입니다.<br /> <br /> (<a target='tab' href='http://www.sysnet.pe.kr/bbs/DownloadAttachment.aspx?fid=918&boardid=331301885'>첨부한 소스코드는 위의 예제를 포함</a>합니다.)<br /> <br /> <hr style='width: 50%' /><br /> <br /> 물론, 그렇긴 하지만 현실적으로 봤을 때 struct 타입에 Equals 메서드를 재정의하지 않아도 크게 문제가 되는 경우는 많지 않으니 너무 걱정하지 않으셔도 됩니다. ^^ 위의 성능 비교에서도 나오지만 10만번 루프 결과에 겨우 저 정도차이라면 극한의 성능을 요구하는 경우를 제외하고는 거의 티도 나지 않습니다.<br /> <br /> 어쨌든, 이제부터라도 좋은 습관을 들이는 것도 나쁘진 않겠지요! ^^<br /> </p><br /> <br /><hr /><span style='color: Maroon'>[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]</span> </div>
첨부파일
스팸 방지용 인증 번호
1940
(왼쪽의 숫자를 입력해야 합니다.)