473,385 Members | 1,732 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Public property or variable ?

Should I use:

Private m_Name As String

Public Property Name() As String
Get
Return m_Name
End Get
Set(ByVal Value As String)
m_Name = Value
End Set
End Property

or just

Public Name As String

The last one just has to be faster, or am I wrong?

Stefan
Nov 21 '05 #1
9 8846
"Stefan De Schepper" <st****************@skynet.be> schrieb:
Should I use:

Private m_Name As String

Public Property Name() As String
Get
Return m_Name
End Get
Set(ByVal Value As String)
m_Name = Value
End Set
End Property

or just

Public Name As String

The last one just has to be faster, or am I wrong?


If 'Name' is an attribute of the entity represented by the class, I strongly
recommend to use a property instead of a public variable.

--
M S Herfried K. Wagner
M V P <URL:http://dotnet.mvps.org/>
V B <URL:http://classicvb.org/petition/>

Nov 21 '05 #2
When you create a Property, you'll have a Set section to write validation
code into. If you just use a Public field any string value passed to it
must be accepted. Properties also help you create your class in a more
object oriented way since the property acts as an abstraction layer to the
internal data. In other words, you'll be creating more of a "black box" if
you use the property.
"Stefan De Schepper" <st****************@skynet.be> wrote in message
news:42**********************@news.skynet.be...
Should I use:

Private m_Name As String

Public Property Name() As String
Get
Return m_Name
End Get
Set(ByVal Value As String)
m_Name = Value
End Set
End Property

or just

Public Name As String

The last one just has to be faster, or am I wrong?

Stefan

Nov 21 '05 #3
There is a major difference between the usefulness of properties and
variables. There are what the others have said about it being more object
oriented and it's true, but there are other reasons.

Let's say, for some reason, you want the Name property to be readonly, you
can't do it with the public variable, but you can with the property. Let's
say you have some bug and you want to log every action in your application,
but using a property you can add a line like Log.WriteLine("SettingName: " &
Value) and there you go. You can't do this neither with the public variable

I hope you get the point and I hope it helps

ThunderMusic

"Stefan De Schepper" <st****************@skynet.be> a écrit dans le message
de news:42**********************@news.skynet.be...
Should I use:

Private m_Name As String

Public Property Name() As String
Get
Return m_Name
End Get
Set(ByVal Value As String)
m_Name = Value
End Set
End Property

or just

Public Name As String

The last one just has to be faster, or am I wrong?

Stefan

Nov 21 '05 #4
As you can see that from the responses, people on this newsgroup don't like
fields but are stuck on properties. I find fields useful in certain
situations and would suggest you use whatever is best for you. As for the
speed, I wrote a test program to read and write to both a string field and a
stirng property where the property was stored as a private variable. I did
this for 10m cycles and found very little difference then upped it to 100m
cycles and found that reading/writing to a field is pretty consistently 120
seconds faster than reading/writing a property on my computer.
--
Dennis in Houston
"Stefan De Schepper" wrote:
Should I use:

Private m_Name As String

Public Property Name() As String
Get
Return m_Name
End Get
Set(ByVal Value As String)
m_Name = Value
End Set
End Property

or just

Public Name As String

The last one just has to be faster, or am I wrong?

Stefan

Nov 21 '05 #5
As for your performance test, it's obvious that working with just the field
will perform better. But, if you read the responses, you'll see why we are
"stuck" on properties. They offer much more security and flexibility than
fields and in all but the most demanding situations does the performance gap
that you mention actually make a difference.
"Dennis" <De****@discussions.microsoft.com> wrote in message
news:FE**********************************@microsof t.com...
As you can see that from the responses, people on this newsgroup don't
like
fields but are stuck on properties. I find fields useful in certain
situations and would suggest you use whatever is best for you. As for
the
speed, I wrote a test program to read and write to both a string field and
a
stirng property where the property was stored as a private variable. I
did
this for 10m cycles and found very little difference then upped it to 100m
cycles and found that reading/writing to a field is pretty consistently
120
seconds faster than reading/writing a property on my computer.
--
Dennis in Houston
"Stefan De Schepper" wrote:
Should I use:

Private m_Name As String

Public Property Name() As String
Get
Return m_Name
End Get
Set(ByVal Value As String)
m_Name = Value
End Set
End Property

or just

Public Name As String

The last one just has to be faster, or am I wrong?

Stefan

Nov 21 '05 #6
ThunderMusic,
| Let's say, for some reason, you want the Name property to be readonly, you
| can't do it with the public variable, but you can with the property.
You can make public & private fields (variables) readonly, by adorning them
with the Readonly keyword. Such as:

Public Readonly Name As String

When you use Readonly on a field you can only set the field in the
constructor.

Public Sub New(ByVal name As String)
Me.Name = name
End Sub

I use readonly fields in my classes when the value of said field is
immutable for the lifetime of that instance of the object. This ensures that
I or one of my predecessors know that the field itself is not meant to
change...

NOTE: Readonly properties with read/write fields are useful for "State"
properties such as SqlConnection.State where the property reports the
"state" of the object, while other methods (Open, Close) modify that
"state".

| but using a property you can add a line like Log.WriteLine("SettingName: "
&
| Value) and there you go. You can't do this neither with the public
variable
Agreed...

Hope this helps
Jay
"ThunderMusic" <NO*******@sympatico.caSPAMATALL> wrote in message
news:%2****************@TK2MSFTNGP14.phx.gbl...
| There is a major difference between the usefulness of properties and
| variables. There are what the others have said about it being more object
| oriented and it's true, but there are other reasons.
|
| Let's say, for some reason, you want the Name property to be readonly, you
| can't do it with the public variable, but you can with the property. Let's
| say you have some bug and you want to log every action in your
application,
| but using a property you can add a line like Log.WriteLine("SettingName: "
&
| Value) and there you go. You can't do this neither with the public
variable
|
| I hope you get the point and I hope it helps
|
| ThunderMusic
|
| "Stefan De Schepper" <st****************@skynet.be> a écrit dans le
message
| de news:42**********************@news.skynet.be...
| > Should I use:
| >
| > Private m_Name As String
| >
| > Public Property Name() As String
| > Get
| > Return m_Name
| > End Get
| > Set(ByVal Value As String)
| > m_Name = Value
| > End Set
| > End Property
| >
| > or just
| >
| > Public Name As String
| >
| > The last one just has to be faster, or am I wrong?
| >
| > Stefan
| >
| >
|
|
Nov 21 '05 #7
Dennis,
| I did
| this for 10m cycles and found very little difference then upped it to 100m
| cycles and found that reading/writing to a field is pretty consistently
120
| seconds faster than reading/writing a property on my computer.

I would expect your results to be closer to zero, as there is a good chance
the JIT will inline the property Getter & Setter.

http://msdn.microsoft.com/library/de...anagedapps.asp

Did you test the Debug or Release build of your app?

Did you test from a command prompt or from Visual Studio?

If you tested the Debug build from Visual Studio, then the JIT will not
attempt to optimize the code. However if you tested the Release build from
the command line then the JIT will attempt to "fully" optimize the code.

Your numbers suggests you tested a Debug build, possible under Visual
Studio!

Try the following from a command prompt for both Debug & Release builds:

Declare Function QueryPerformanceCounter Lib "Kernel32" (ByRef X As
Long) As Short
Declare Function QueryPerformanceFrequency Lib "Kernel32" (ByRef X As
Long) As Short

Private Class Person

Public m_name As String

Public Sub New(ByVal name As String)
m_name = name
End Sub

Public Property Name() As String
Get
Return m_name
End Get
Set(ByVal value As String)
m_name = value
End Set
End Property
End Class

Public Shared Sub Main()
Const MaxCount As Integer = 1000000
Const format As String = "{1}: {0}"

Dim aPerson As New Person("Jay")

For outerCount As Integer = 1 To 5
Dim start, finish, frequency As Long
QueryPerformanceFrequency(frequency)

QueryPerformanceCounter(start)
For innerCount As Integer = 1 To MaxCount
aPerson.Name = "Fred"
Next
QueryPerformanceCounter(finish)
Console.WriteLine(format, TimeSpan.FromSeconds((finish - start)
/ frequency), "Property")

QueryPerformanceCounter(start)
For innerCount As Integer = 1 To MaxCount
aPerson.m_name = "Fred"
Next
QueryPerformanceCounter(finish)
Console.WriteLine(format, TimeSpan.FromSeconds((finish - start)
/ frequency), "Field")
Next

End Sub

For Debug builds you should see Property much larger then Field. For Release
builds you should see both numbers nearly the same.

Hope this helps
Jay


"Dennis" <De****@discussions.microsoft.com> wrote in message
news:FE**********************************@microsof t.com...
| As you can see that from the responses, people on this newsgroup don't
like
| fields but are stuck on properties. I find fields useful in certain
| situations and would suggest you use whatever is best for you. As for
the
| speed, I wrote a test program to read and write to both a string field and
a
| stirng property where the property was stored as a private variable. I
did
| this for 10m cycles and found very little difference then upped it to 100m
| cycles and found that reading/writing to a field is pretty consistently
120
| seconds faster than reading/writing a property on my computer.
| --
| Dennis in Houston
|
|
| "Stefan De Schepper" wrote:
|
| > Should I use:
| >
| > Private m_Name As String
| >
| > Public Property Name() As String
| > Get
| > Return m_Name
| > End Get
| > Set(ByVal Value As String)
| > m_Name = Value
| > End Set
| > End Property
| >
| > or just
| >
| > Public Name As String
| >
| > The last one just has to be faster, or am I wrong?
| >
| > Stefan
| >
| >
| >
Nov 21 '05 #8
Stefan,
In addition to the other comments.

| The last one just has to be faster, or am I wrong?
Your wrong! The JIT compiler has the option to inline the property Get & Set
routines (actually any short method). Which means the Property will execute
exactly the same as a Field! See my response to Dennis on details & a
demonstration.

http://msdn.microsoft.com/library/de...anagedapps.asp

I would be more concerned about what is "correct". The property suggests
better encapsulation, remember Encapsulation is one of the major tenants of
OO.

Properties also play nicer with System.ComponentModel,
System.Windows.Forms.PropertyGrid and COM interop.

I would not code a field or property based on perceived runtime performance.

Remember the 80/20 rule. That is 80% of the execution time of your program
is spent in 20% of your code. I will optimize (worry about performance,
memory consumption) the 20% once that 20% has been identified & proven to be
a performance problem via profiling (CLR Profiler is one profiling tool).

For info on the 80/20 rule & optimizing only the 20% see Martin Fowler's
article "Yet Another Optimization Article" at
http://martinfowler.com/ieeeSoftware...timization.pdf

Here are some thoughts on not using properties:

http://blogs.msdn.com/ericgu/archive...29/123588.aspx
Hope this helps
Jay
"Stefan De Schepper" <st****************@skynet.be> wrote in message
news:42**********************@news.skynet.be...
| Should I use:
|
| Private m_Name As String
|
| Public Property Name() As String
| Get
| Return m_Name
| End Get
| Set(ByVal Value As String)
| m_Name = Value
| End Set
| End Property
|
| or just
|
| Public Name As String
|
| The last one just has to be faster, or am I wrong?
|
| Stefan
|
|
Nov 21 '05 #9
You are correct in that I tested it in debug mode. As for using Properties
vs Fields, I fully understand the consequences of using one over the other so
I use what works for me in a particulair situation. I'm not a purist and I
know there are several ways to skin a cat! If I have a class that contains
something like a boolean value and it's independent of whatever else is in
the class, I see no reason to not just use a field.

--
Dennis in Houston
"Jay B. Harlow [MVP - Outlook]" wrote:
Dennis,
| I did
| this for 10m cycles and found very little difference then upped it to 100m
| cycles and found that reading/writing to a field is pretty consistently
120
| seconds faster than reading/writing a property on my computer.

I would expect your results to be closer to zero, as there is a good chance
the JIT will inline the property Getter & Setter.

http://msdn.microsoft.com/library/de...anagedapps.asp

Did you test the Debug or Release build of your app?

Did you test from a command prompt or from Visual Studio?

If you tested the Debug build from Visual Studio, then the JIT will not
attempt to optimize the code. However if you tested the Release build from
the command line then the JIT will attempt to "fully" optimize the code.

Your numbers suggests you tested a Debug build, possible under Visual
Studio!

Try the following from a command prompt for both Debug & Release builds:

Declare Function QueryPerformanceCounter Lib "Kernel32" (ByRef X As
Long) As Short
Declare Function QueryPerformanceFrequency Lib "Kernel32" (ByRef X As
Long) As Short

Private Class Person

Public m_name As String

Public Sub New(ByVal name As String)
m_name = name
End Sub

Public Property Name() As String
Get
Return m_name
End Get
Set(ByVal value As String)
m_name = value
End Set
End Property
End Class

Public Shared Sub Main()
Const MaxCount As Integer = 1000000
Const format As String = "{1}: {0}"

Dim aPerson As New Person("Jay")

For outerCount As Integer = 1 To 5
Dim start, finish, frequency As Long
QueryPerformanceFrequency(frequency)

QueryPerformanceCounter(start)
For innerCount As Integer = 1 To MaxCount
aPerson.Name = "Fred"
Next
QueryPerformanceCounter(finish)
Console.WriteLine(format, TimeSpan.FromSeconds((finish - start)
/ frequency), "Property")

QueryPerformanceCounter(start)
For innerCount As Integer = 1 To MaxCount
aPerson.m_name = "Fred"
Next
QueryPerformanceCounter(finish)
Console.WriteLine(format, TimeSpan.FromSeconds((finish - start)
/ frequency), "Field")
Next

End Sub

For Debug builds you should see Property much larger then Field. For Release
builds you should see both numbers nearly the same.

Hope this helps
Jay


"Dennis" <De****@discussions.microsoft.com> wrote in message
news:FE**********************************@microsof t.com...
| As you can see that from the responses, people on this newsgroup don't
like
| fields but are stuck on properties. I find fields useful in certain
| situations and would suggest you use whatever is best for you. As for
the
| speed, I wrote a test program to read and write to both a string field and
a
| stirng property where the property was stored as a private variable. I
did
| this for 10m cycles and found very little difference then upped it to 100m
| cycles and found that reading/writing to a field is pretty consistently
120
| seconds faster than reading/writing a property on my computer.
| --
| Dennis in Houston
|
|
| "Stefan De Schepper" wrote:
|
| > Should I use:
| >
| > Private m_Name As String
| >
| > Public Property Name() As String
| > Get
| > Return m_Name
| > End Get
| > Set(ByVal Value As String)
| > m_Name = Value
| > End Set
| > End Property
| >
| > or just
| >
| > Public Name As String
| >
| > The last one just has to be faster, or am I wrong?
| >
| > Stefan
| >
| >
| >

Nov 21 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Will Gillen | last post by:
I know this has probably been asked before, but I can't seem to find a solid answer in any of the archives. First, before my question, please forgive my limited knowledge of the event lifecycle...
0
by: student | last post by:
In Summary: Create an object - dont set one of its Enum Type properties and make sure it does not appear in XML Object Serialization. Strings function as hoped for but Enums do not Heres my...
4
by: funVB2005fun | last post by:
I am not quite sure what I am getting into but I would like to have a loop that read from a flat file to create some public properties in a class. I am going after this to try and create more...
2
by: Richard | last post by:
I'm trying to open a form based on the value that I am passing through to it. I'm trying to open the Deals form on the basis of a sellerid that I am trying to pass through to that second form. ...
2
by: miben | last post by:
I need to set a variable returned by a readonly property in a class by another class. So the only way to set that value is from a specific class and function. Public Sub Main Dim setter As New...
4
by: Jon Paal | last post by:
I have a public property in my server control and I want to populate it with values generated by the control. When I assign the value of the property to a function in the control, which creates...
3
by: jbeteta | last post by:
Hello, I have a problem declaring variables. I need to create an object oRpte as ReportClass on WebForm1.aspx and be able to use its value on WebForm2.aspx. For declaring the property oRpte()...
6
by: =?Utf-8?B?SmF5IFBvbmR5?= | last post by:
I am trying to access a Public property on a Master Page from a Base Page. On the content pages I have the MasterType Directive set up as follows: <%@ MasterType virtualpath="~/Master.master" %>...
0
by: abev | last post by:
I am still trying to get my arms around properties and why I should use them more. But I just cannot understand when I should be using properties as opposed to just declaring a 'public shared'...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.