Efficiency, Refactoring, and Compilation in VB.NET

  • Thread starter Thread starter Nathan Sokalski
  • Start date Start date
N

Nathan Sokalski

When a property is declared in VB.NET using the Property keyword as follows:


Public Property Text() As String
Get
Return Me._text
End Get
Set(ByVal value As String)
Me.text = value
End Set
End Property


The Get or Set methods get called when doing something like:

Dim x As String = Me.Text
Me.Text = "blahblahblah"

This could obviously be rewritten as:

Dim x As String = Me._text
Me._text = "blahblahblah"

so that it directly access the variable where the value is stored to bypass
calling a method. However, if I were to add something to the Get and/or set
methods in the future, I would need to go back and change all these to use
the Get and Set methods. My question is when a Property is when the Get and
Set methods are straightforward Return storagevariable and
storagevariable=value, does the VB.NET compiler refactor this to bypass the
extra step of executing a method? Thanks.
 
Nathan Sokalski said:
When a property is declared in VB.NET using the Property keyword as
follows:


Public Property Text() As String
Get
Return Me._text
End Get
Set(ByVal value As String)
Me.text = value

I assume you meant 'Me._text = value'.
End Set
End Property


The Get or Set methods get called when doing something like:

Dim x As String = Me.Text
Me.Text = "blahblahblah"

This could obviously be rewritten as:

Dim x As String = Me._text
Me._text = "blahblahblah"

so that it directly access the variable where the value is stored to
bypass calling a method. However, if I were to add something to the Get
and/or set methods in the future, I would need to go back and change all
these to use the Get and Set methods. My question is when a Property is
when the Get and Set methods are straightforward Return storagevariable
and storagevariable=value, does the VB.NET compiler refactor this to
bypass the extra step of executing a method?

I think the speed difference would be marginal. However, the JIT compiler
may inline the property call. I suggest to never access the property value
(backing field) directly except in the property's set and get part.
Otherwise property value validation code introduced later on would be
bypassed and it would be possible to assign an invalid property value.
 
Back
Top