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

비밀번호

댓글 작성자
 




... 61  62  63  64  65  66  67  68  69  70  71  [72]  73  74  75  ...
NoWriterDateCnt.TitleFile(s)
11833정성태3/4/201913671개발 환경 구성: 431. Visual Studio 2019 - CMake를 이용한 공유/실행(so/out) 리눅스 프로젝트 설정파일 다운로드1
11832정성태3/4/201910733오류 유형: 524. Visual Studio CMake - rsync: connection unexpectedly closed
11831정성태3/4/201910285오류 유형: 523. Visual Studio 2019 - 새 창으로 뜬 윈도우를 닫을 때 비정상 종료
11830정성태2/26/201910121오류 유형: 522. 이벤트 로그 - Error opening event log file State. Log will not be processed. Return code from OpenEventLog is 87.
11829정성태2/26/201911976개발 환경 구성: 430. 마이크로소프트의 CoreCLR 프로파일러 예제 빌드 방법 - 리눅스 환경 [1]
11828정성태2/26/201918366개발 환경 구성: 429. Component Services 관리자의 RuntimeBroker 설정이 2개 있는 경우 [8]
11827정성태2/26/201912302오류 유형: 521. Visual Studio - Could not start the 'rsync' command on the remote host, please install it using your system package manager.
11826정성태2/26/201912227오류 유형: 520. 우분투에 .NET Core SDK 설치 시 패키지 의존성 오류
11825정성태2/25/201917077개발 환경 구성: 428. Visual Studio 2019 - CMake를 이용한 리눅스 빌드 환경 설정 [1]
11824정성태2/25/201911847오류 유형: 519. The SNMP Service encountered an error while accessing the registry key SYSTEM\CurrentControlSet\Services\SNMP\Parameters\TrapConfiguration. [1]
11823정성태2/21/201913299오류 유형: 518. IIS 관리 콘솔이 뜨지 않는 문제
11822정성태2/20/201911470오류 유형: 517. docker에 설치한 MongoDB 서버로 연결이 안 되는 경우
11821정성태2/20/201911941오류 유형: 516. Visual Studio 2019 - This extension uses deprecated APIs and is at risk of not functioning in a future VS update. [1]
11820정성태2/20/201915050오류 유형: 515. 윈도우 10 1809 업데이트 후 "User Profiles Service" 1534 경고 발생
11819정성태2/20/201913720Windows: 158. 컴퓨터와 사용자의 SID(security identifier) 확인 방법
11818정성태2/20/201912643VS.NET IDE: 131. Visual Studio 2019 Preview의 닷넷 프로젝트 빌드가 20초 이상 걸리는 경우 [2]
11817정성태2/17/20199841오류 유형: 514. WinDbg Preview 실행 오류 - Error : DbgX.dll : WindowsDebugger.WindowsDebuggerException: Could not load dbgeng.dll
11816정성태2/17/201912314Windows: 157. 윈도우 스토어 앱(Microsoft Store App)을 명령행에서 직접 실행하는 방법
11815정성태2/14/201911234오류 유형: 513. Visual Studio 2019 - VSIX 설치 시 "The extension cannot be installed to this product due to prerequisites that cannot be resolved." 오류 발생
11814정성태2/12/20199991오류 유형: 512. VM(가상 머신)의 NT 서비스들이 자동 시작되지 않는 문제
11813정성태2/12/201911594.NET Framework: 809. C# - ("Save File Dialog" 등의) 대화 창에 확장 속성을 보이는 방법
11812정성태2/11/20199490오류 유형: 511. Windows Server 2003 VM 부팅 후 로그인 시점에 0xC0000005 BSOD 발생
11811정성태2/11/201913195오류 유형: 510. 서버 운영체제에 NVIDIA GeForce Experience 실행 시 wlanapi.dll 누락 문제
11810정성태2/11/201911270.NET Framework: 808. .NET Profiler - GAC 모듈에서 GAC 비-등록 모듈을 참조하는 경우의 문제
11809정성태2/11/201912731.NET Framework: 807. ClrMD를 이용해 메모리 덤프 파일로부터 특정 인스턴스를 참조하고 있는 소유자 확인
11808정성태2/8/201913856디버깅 기술: 123. windbg - 닷넷 응용 프로그램의 메모리 누수 분석
... 61  62  63  64  65  66  67  68  69  70  71  [72]  73  74  75  ...