Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)

struct로 정의한 값 형식(Value Type)의 경우 Equals 재정의를 권장합니다.

다음과 같은 코드를 볼까요!

using System;

class Program
{
    static void Main(string[] args)
    {
        MyStruct ms1 = new MyStruct { _n = 5 };
        MyStruct ms2 = new MyStruct { _n = 5 };

        Console.WriteLine(ms1.Equals(ms2)); // True
    }
}

struct MyStruct
{
    public int _n;
}

기본적인 System.Object 타입의 Equals 메서드는 .NET Reflector로 살펴보면 RuntimeHelpers.Equals 호출로 연결됩니다.

[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries"), __DynamicallyInvokable]
public virtual bool Equals(object obj)
{
    return RuntimeHelpers.Equals(this, obj);
}
        
[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)));
}

하지만, struct로 정의한 C# 타입은 System.Object가 아닌 System.ValueType을 부모 클래스로 지정되기 때문에 그 클래스에 재정의된 Equals 메서드가 실행됩니다. 그 코드가 재미있는데요.

[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);
    }
    FieldInfo[] fields = type.GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
    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;
}

보는 바와 같이 Reflection을 통해 일일이 값 비교를 하고 있습니다. Reflection이 느리다는 것은 다들 아실텐데요, 따라서 당연히 다음과 같이 Equals 메서드를 재정의해주는 것이 실행 속도가 더 빠릅니다.

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;

    public override bool Equals(object obj)
    {
        MyStructWithEquals target = (MyStructWithEquals)obj;
        return _n == target._n;                
    }

    public override int GetHashCode()
    {
        return _n.GetHashCode();
    }
}

실제로 성능 비교를 해볼까요? ^^

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

실행해 보면?

CompareTime1 - # of 100000: 16895
CompareTime2 - # of 100000: 3165

CompareTime1 - # of 1000000: 108633
CompareTime2 - # of 1000000: 34897

CompareTime1 - # of 10000000: 1108970
CompareTime2 - # of 10000000: 332720

약 3배 이상의 성능 차이가 나는 것을 볼 수 있습니다.




Equals 메서드를 잘 쓰지 않는 듯 해도, 알게 모르게 사용되는 경우가 있습니다. 바로 Dictionary 류의 자료 구조를 사용할 때입니다. 일례로, 다음과 같이 HashSet을 사용하는 경우,

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 };

        HashSet<MyStructWithEquals> hs2 = new HashSet<MyStructWithEquals>();
        hs2.Add(msw1);
        hs2.Add(msw2);
    }
}

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

HashSet.Add, MyStructWithEquals.GetHashCode, MyStructWithEquals.Equals 메서드에 BP(Breakpoint)를 걸고 F11 키를 누르면, Add -> GetHashCode -> Equals 순으로 실행이 되는 것을 확인할 수 있습니다. 즉, 여러분들이 Dictionary 류의 자료 구조를 사용한다면 필연적으로 Equals/GetHashCode 메서드가 불리게 되고, 이것을 재정의하지 않았다면 닷넷은 기본 구현체인 Reflection을 이용한 비교 작업을 수행하게 되는 것입니다.

(첨부한 소스코드는 위의 예제를 포함합니다.)




물론, 그렇긴 하지만 현실적으로 봤을 때 struct 타입에 Equals 메서드를 재정의하지 않아도 크게 문제가 되는 경우는 많지 않으니 너무 걱정하지 않으셔도 됩니다. ^^ 위의 성능 비교에서도 나오지만 10만번 루프 결과에 겨우 저 정도차이라면 극한의 성능을 요구하는 경우를 제외하고는 거의 티도 나지 않습니다.

어쨌든, 이제부터라도 좋은 습관을 들이는 것도 나쁘진 않겠지요! ^^




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 2/23/2015]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 91  92  93  94  95  96  97  98  99  100  101  102  103  [104]  105  ...
NoWriterDateCnt.TitleFile(s)
11040정성태9/10/201618988.NET Framework: 604. C# Windows Forms - Drag & Drop 예제 코드 [2]파일 다운로드1
11039정성태9/9/201616204오류 유형: 355. Visual Studio 빌드 오류 - error CS0122: '__ComObject' is inaccessible due to its protection level
11038정성태9/9/201617293VC++: 99. 서로 다른 프로세스에서 WM_DROPFILES 메시지를 전송하는 방법파일 다운로드1
11037정성태9/8/201620513.NET Framework: 603. socket - shutdown 호출이 필요한 사례파일 다운로드1
11036정성태8/29/201617516개발 환경 구성: 297. 소스 코드가 없는 닷넷 어셈블리를 디버깅할 때 지역 변숫값을 확인하는 방법
11035정성태8/29/201613552오류 유형: 354. .NET Reflector - PDB 생성 화면에서 "Clear Store"를 하면 "Index and length must refer to a location within the string" 예외 발생
11034정성태8/25/201617244개발 환경 구성: 296. .NET Core 프로젝트를 NuGet Gallery에 배포하는 방법 [2]
11033정성태8/24/201615065오류 유형: 353. coreclr 빌드 시 error C3249: illegal statement or sub-expression for 'constexpr' function
11032정성태8/23/201614509개발 환경 구성: 295. 최신의 Visual C++ 컴파일러 도구를 사용하는 방법 [1]
11031정성태8/23/201611593오류 유형: 352. Error encountered while pushing to the remote repository: Response status code does not indicate success: 403 (Forbidden).
11030정성태8/23/201613361VS.NET IDE: 111. Team Explorer - 추가한 Git Remote 저장소가 Branch에 보이지 않는 경우
11029정성태8/18/201619835.NET Framework: 602. Process.Start의 cmd.exe에서 stdin만 redirect 하는 방법 [1]파일 다운로드1
11028정성태8/15/201614837오류 유형: 351. Octave 설치 시 JRE 경로 문제
11027정성태8/15/201615698.NET Framework: 601. ElementHost 컨트롤의 메모리 누수 현상
11026정성태8/13/201616348Math: 19. 행렬 연산으로 본 해밍코드
11025정성태8/12/201614957개발 환경 구성: 294. .NET Core 프로젝트에서 "Copy to Output Directory" 처리 [1]
11024정성태8/12/201615360오류 유형: 350. "nProtect GameMon" 실행 중에는 Visual Studio 디버깅이 안됩니다! [1]
11023정성태8/10/201616150개발 환경 구성: 293. Azure 구독 후 PaaS 서비스 만들어 보기
11022정성태8/10/201616473개발 환경 구성: 292. Azure Cloud Service 배포시 사용자 정의 작업을 추가하는 방법
11021정성태8/10/201614163오류 유형: 349. System.Runtime.Remoting.RemotingException - Type '..., ..., Version=..., Culture=neutral, PublicKeyToken=null' is not registered for activation [2]
11020정성태8/10/201615979VC++: 98. 원본과 대상 버퍼가 같은 경우 memcpy, wmemcpy 주의점
11019정성태8/10/201630906기타: 60. 도서: 시작하세요! C# 6.0 프로그래밍: 기본 문법부터 실전 예제까지 (2쇄 정오표)
11018정성태8/9/201616683.NET Framework: 600. 단일 메서드 내에서의 할당으로 알아보는 자바와 닷넷의 GC 차이점 [1]
11017정성태8/9/201619788웹: 33. HTTP 쿠키에 한글 값을 설정하는 방법
11016정성태8/7/201616703개발 환경 구성: 291. Windows Server Containers 소개
11015정성태8/7/201615087오류 유형: 348. Windows Server 2016 TP5에서 Windows Containers의 docker run 실행 시 encountered an error during Start failed in Win32
... 91  92  93  94  95  96  97  98  99  100  101  102  103  [104]  105  ...