简体   繁体   中英

Get-only property with constant value, auto-property or not?

Is there a performance/memory usage difference between the two following property declarations, and should one be preferred?

public bool Foo => true;

public bool Foo { get; } = true;

Also, does the situation change if the Boolean is replaced with a different immutable value (eg string)?

I wrote this class as an example

class Program
{
    public bool A => true;
    public bool B { get; } = true;
}

with reflection I decompiled the assembly and get this code

class Program
{
    // Fields
    [CompilerGenerated, DebuggerBrowsable(DebuggerBrowsableState.Never)]
    private readonly bool <B>k__BackingField = true;

    public bool A
    {
        get
        {
            return true;
        }
    }

    public bool B
    {
        [CompilerGenerated]
        get
        {
            return this.<B>k__BackingField;
        }
    }
}

So as @Fruchtzwerg mentioned both ways have the same way to return the value BUT the difference is in the implementation of getter methods since one return the value ture and the other return a field which has the value true .

Talking about performance and memory the first way seems to be better, but if you only need this property to be true I suggest to use const .

I created a simple example to show the difference. I created the two classes A and B with the different property implementations.

public class A
{
    public bool Foo => true;
}

public class B
{
    public bool Foo { get; } = true;
}

A simple test code using the classes should be enought to show the differences at the generated CIL code:

A a = new A();
B b = new B();

bool c;
c = a.Foo;
c = b.Foo;

Disassembly is showing the following code:

            c = a.Foo;
00C50FB0  mov         ecx,dword ptr [ebp-40h]  
00C50FB3  cmp         dword ptr [ecx],ecx  
00C50FB5  call        00C50088  
00C50FBA  mov         dword ptr [ebp-54h],eax  
00C50FBD  movzx       eax,byte ptr [ebp-54h]  
00C50FC1  mov         dword ptr [ebp-48h],eax  
            c = b.Foo;
00C50FC4  mov         ecx,dword ptr [ebp-44h]  
00C50FC7  cmp         dword ptr [ecx],ecx  
00C50FC9  call        00C500A8  
00C50FCE  mov         dword ptr [ebp-58h],eax  
00C50FD1  movzx       eax,byte ptr [ebp-58h]  
00C50FD5  mov         dword ptr [ebp-48h],eax

This means there is no difference (except the getter in line 3 --> Have a look at @Arvins answer). Also changing the type is resulting in exactly the same CIL code at both implementations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM