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)
11090정성태11/1/201620816VC++: 103. C++ CreateTimerQueue, CreateTimerQueueTimer 예제 코드 [9]파일 다운로드1
11089정성태11/1/201619464디버깅 기술: 82. Windows 10을 위한 Symbol(PDB) 파일 내려받는 방법 [2]
11088정성태11/1/201624165.NET Framework: 617. C# - AForge.NET을 이용한 MP4 동영상 파일 재생 [7]파일 다운로드1
11087정성태11/1/201618498.NET Framework: 616. AForge.Video.FFMPEG를 최신 버전의 ffmpeg 파일로 의존성을 변경하는 방법파일 다운로드1
11086정성태11/1/201612330오류 유형: 366. The Microsoft Passport Container service terminated with the following error: General access denied error
11085정성태10/27/201625835.NET Framework: 615. C# - AForge.NET을 이용한 웹캠 영상 출력 [2]파일 다운로드1
11084정성태10/26/201614465오류 유형: 365. The User Profile Service service failed to the sign-in.
11083정성태10/26/201620870Windows: 131. 윈도우 10에서 사라진 "Adapters and Bindings" 네트워크 우선 순위 조정 기능 [1]
11082정성태10/26/201621774.NET Framework: 614. C# - DateTime.Ticks의 정밀도 [4]파일 다운로드1
11081정성태10/26/201613426오류 유형: 364. You need to fix your Microsoft Account for apps on your other devices to be able to launch apps and continue experiences on this device.
11080정성태10/24/201616443Windows: 130. Windows Server 2016 Nano 서버 설치 방법
11079정성태10/21/201613567Windows: 129. Windows Server 2016 설치 CD에 있는 Convert-WindowsImage.ps1 사용 방법 정리
11078정성태10/21/201615045Windows: 128. Windows Server 2016 Nano 서버 VHD 이미지 만드는 방법 - TP5 기준
11077정성태10/21/201614296오류 유형: 363. Active Directory 서버의 NETLOGON 서비스가 멈췄을 때 발생하는 문제
11076정성태10/21/201613100오류 유형: 362. 윈도우 백업 시 오류 - 0x80780040
11075정성태10/20/201614580Windows: 127. Convert-WindowsImage.ps1 사용 방법 정리
11074정성태10/20/201621987Windows: 126. Windows Server 2016 평가판을 정식 버전으로 라이선스 변경하는 방법
11073정성태10/20/201617525.NET Framework: 613. 윈도우 데스크톱 응용 프로그램(예: Console)에서 알림 메시지(Toast notifications) 띄우기 [1]파일 다운로드1
11072정성태10/20/201614229VC++: 102. 새로 추가한 ATL COM 객체가 regsvr32.exe로 등록이 안되는 문제
11071정성태10/20/201617452.NET Framework: 612. UWP(유니버설 윈도우 플랫폼) 앱에서 콜백 함수 내에서의 UI 요소 접근 방법 [1]
11070정성태10/20/201612768Windows: 125. 윈도우 서버 2016 마이그레이션
11069정성태10/19/201619990.NET Framework: 611. C++ 개발자들을 위한 C# Thread 동작 방식 [2]
11068정성태10/19/201622951Windows: 124. 윈도우 운영체제의 시간 함수 (5) - TSC(Time Stamp Counter)와 QueryPerformanceCounter [12]파일 다운로드1
11067정성태10/18/201619880Windows: 123. 윈도우 운영체제의 시간 함수 (4) - RTC, TSC, PM Clock, HPET Timer [2]
11066정성태10/17/201617083Windows: 122. 윈도우 운영체제의 시간 함수 (3) - QueryInterruptTimePrecise, QueryInterruptTime 함수파일 다운로드1
11065정성태10/15/201622268Windows: 121. 윈도우 운영체제의 시간 함수 (2) - Sleep 함수의 동작 방식 [1]
... 91  92  93  94  95  96  97  98  99  100  101  [102]  103  104  105  ...