programing

INotifyPropertyChanged를 구현할 때 [CallerMemberName]이 대안에 비해 느립니까?

nasanasas 2020. 9. 7. 08:14
반응형

INotifyPropertyChanged를 구현할 때 [CallerMemberName]이 대안에 비해 느립니까?


구현을위한 다양한 방법을INotifyPropertyChanged 제안하는 좋은 기사가 있습니다.

다음 기본 구현을 고려하십시오.

class BasicClass : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private void FirePropertyChanged(string propertyName)
    {
        var handler = PropertyChanged;
        if (handler != null)
            handler(this, new PropertyChangedEventArgs(propertyName));
    }

    private int sampleIntField;

    public int SampleIntProperty
    {
        get { return sampleIntField; }
        set
        {
            if (value != sampleIntField)
            {
                sampleIntField = value;
                FirePropertyChanged("SampleIntProperty"); // ouch ! magic string here
            }
        }
    }
}

나는 이것을 다음으로 바꾸고 싶습니다.

using System.Runtime.CompilerServices;

class BetterClass : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    // Check the attribute in the following line :
    private void FirePropertyChanged([CallerMemberName] string propertyName = null)
    {
        var handler = PropertyChanged;
        if (handler != null)
            handler(this, new PropertyChangedEventArgs(propertyName));
    }

    private int sampleIntField;

    public int SampleIntProperty
    {
        get { return sampleIntField; }
        set
        {
            if (value != sampleIntField)
            {
                sampleIntField = value;
                // no "magic string" in the following line :
                FirePropertyChanged();
            }
        }
    }
}

그러나 때때로 나는 [CallerMemberName]속성이 대안에 비해 성능이 좋지 않다는 것을 읽었습니다 . 그게 사실이고 그 이유는 무엇입니까? 반사를 사용합니까?


아니요, 의 사용은[CallerMemberName] 상위 기본 구현보다 느리지 않습니다 .

MSDN 페이지에 따르면

호출자 정보 값은 컴파일 타임에 IL (Intermediate Language)에 리터럴로 내보내집니다.

We can check that with any IL disassembler (like ILSpy) : the code for the "SET" operation of the property is compiled exactly the same way : Decompiled property with CallerMemberName

So no use of Reflection here.

(sample compiled with VS2013)

참고URL : https://stackoverflow.com/questions/22580623/is-callermembername-slow-compared-to-alternatives-when-implementing-inotifypro

반응형