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)
12098정성태1/2/202010918.NET Framework: 874. C# - 커널 구조체의 Offset 값을 하드 코딩하지 않고 사용하는 방법 [3]
12097정성태1/2/20209475디버깅 기술: 150. windbg - Wow64, x86, x64에서의 커널 구조체(예: TEB) 구조체 확인
12096정성태12/30/201911497디버깅 기술: 149. C# - DbgEng.dll을 이용한 간단한 디버거 제작 [1]
12095정성태12/27/201912796VC++: 135. C++ - string_view의 동작 방식
12094정성태12/26/201910979.NET Framework: 873. C# - 코드를 통해 PDB 심벌 파일 다운로드 방법
12093정성태12/26/201911043.NET Framework: 872. C# - 로딩된 Native DLL의 export 함수 목록 출력파일 다운로드1
12092정성태12/25/201910456디버깅 기술: 148. cdb.exe를 이용해 (ntdll.dll 등에 정의된) 커널 구조체 출력하는 방법
12091정성태12/25/201911962디버깅 기술: 147. pdb 파일을 다운로드하기 위한 symchk.exe 실행에 필요한 최소 파일 [1]
12090정성태12/24/201910572.NET Framework: 871. .NET AnyCPU로 빌드된 PE 헤더의 로딩 전/후 차이점 [1]파일 다운로드1
12089정성태12/23/201911333디버깅 기술: 146. gflags와 _CrtIsMemoryBlock을 이용한 Heap 메모리 손상 여부 체크
12088정성태12/23/201910294Linux: 28. Linux - 윈도우의 "Run as different user" 기능을 shell에서 실행하는 방법
12087정성태12/21/201910768디버깅 기술: 145. windbg/sos - Dictionary의 entries 배열 내용을 모두 덤프하는 방법 (do_hashtable.py) [1]
12086정성태12/20/201912793디버깅 기술: 144. windbg - Marshal.FreeHGlobal에서 발생한 덤프 분석 사례
12085정성태12/20/201910496오류 유형: 586. iisreset - The data is invalid. (2147942413, 8007000d) 오류 발생 - 두 번째 이야기 [1]
12084정성태12/19/201911158디버깅 기술: 143. windbg/sos - Hashtable의 buckets 배열 내용을 모두 덤프하는 방법 (do_hashtable.py) [1]
12083정성태12/17/201912434Linux: 27. linux - lldb를 이용한 .NET Core 응용 프로그램의 메모리 덤프 분석 방법 [2]
12082정성태12/17/201912233오류 유형: 585. lsof: WARNING: can't stat() fuse.gvfsd-fuse file system
12081정성태12/16/201913956개발 환경 구성: 465. 로컬 PC에서 개발 중인 ASP.NET Core 웹 응용 프로그램을 다른 PC에서도 접근하는 방법 [5]
12080정성태12/16/201911899.NET Framework: 870. C# - 프로세스의 모든 핸들을 열람
12079정성태12/13/201913077오류 유형: 584. 원격 데스크톱(rdp) 환경에서 다중 또는 고용량 파일 복사 시 "Unspecified error" 오류 발생
12078정성태12/13/201913083Linux: 26. .NET Core 응용 프로그램을 위한 메모리 덤프 방법 [3]
12077정성태12/13/201912573Linux: 25. 자주 실행할 명령어 또는 초기 환경을 "~/.bashrc" 파일에 등록
12076정성태12/12/201910793디버깅 기술: 142. Linux - lldb 환경에서 sos 확장 명령어를 이용한 닷넷 프로세스 디버깅 - 배포 방법에 따른 차이
12075정성태12/11/201911621디버깅 기술: 141. Linux - lldb 환경에서 sos 확장 명령어를 이용한 닷넷 프로세스 디버깅
12074정성태12/10/201911272디버깅 기술: 140. windbg/Visual Studio - 값이 변경된 경우를 위한 정지점(BP) 설정(Data Breakpoint)
12073정성태12/10/201913084Linux: 24. Linux/C# - 실행 파일이 아닌 스크립트 형식의 명령어를 Process.Start로 실행하는 방법
... [61]  62  63  64  65  66  67  68  69  70  71  72  73  74  75  ...