Reputation: 18600
Is there more overhead (i.e memory, CPU, additional IL, etc.) when using a simple1 property over a member?
1Accessibility of the "getters" and "setters" are the same. No additional logic happens in the getter and setter, other than storing the value in memory.
Private CustomerId as Integer
Public CustomerName as String
vs.
Private Property CustomerId as Integer
Public Property CustomerName as String
Upvotes: 0
Views: 32
Reputation: 68670
The overhead, if any, is minimal.
As you may already know, a getter is translated to a method that reads a private backing field, something like this:
private int <Age>k__BackingField;
public int get_Age()
{
return <Age>k__BackingField;
}
Since this method has no logic in it, other than a simple return statement, there's a very high chance calls to this method will be inlined by the jitter. When this happens, there is no overhead at all.
Even when the jitter, for some reason, decides not to perform the method call inline, the overhead is really, really small, I highly doubt you'd notice the difference by looking at a benchmark.
Upvotes: 0
Reputation: 10708
Running the ILDasm tool against the following code:
public class Access
{
public int NumberField;
public int NumberProp { get; set; }
}
results in the following IL for the field
.field public int32 NumberField
And the following for the property
.field private int32 '<NumberProp>k__BackingField'
.custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 )
.method public hidebysig specialname instance int32
get_NumberProp() cil managed
{
// Omitting the entire IL code
} // end of method Access::get_NumberProp
.method public hidebysig specialname instance void
set_NumberProp(int32 'value') cil managed
{
// Omitting entire IL code
} // end of method Access::set_NumberProp
So, in short, the entire idea of a "Simple" Property as you've defined doesn't actually exist once the compiler has it's way - it inserts the k_BackingField value, and creates a getter/setter which accesses/sets that backing field. Note that even in the simple case you can attach method-only attributes to your get/set functions.
To thus answer your question, yes, there is more overhead, because that get/set still result in method calls. EDIT: These calls, as pointed out by contactmatt, may be inlined by the JIT Compiler, which reduces the already minimal overhead to zero.
For similar looks into compiler magic and sugar, also check out how a Lambda capture looks after IL
Upvotes: 3