473,387 Members | 3,821 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,387 software developers and data experts.

Variable Declaration - Does Location Matter?

Is there any difference between declaring a variable at the top of a method
versus in the code of the method? Is there a performance impact for either
choice? What about if the method will return before the variable is used?
I'm trying to get an idea of whether the .NET compilers for VB.NET and C#
will move all variable declaration to the beginning of a method or whether
they will allocate the memory as it is needed by the method to conserve
memory.

Example (VB.NET):
' Declaration at the top of a method.
Public Sub SampleSub()
Dim sMessage As String
' ... Other code that might exit the method early ...
sMessage = "Hello!"
End Sub

' Declaration in a method.
Public Sub SampleSub()
' ... Code that might exit the method early ...
Dim sMessage As String = "Hello!"
End Sub
Jul 21 '05 #1
7 2621
In your case, they are syntactically identical. However, in the following
code, they aren't:

Public Sub SampleSub()
dim sMessage as String ' sMessage is available throughout SampleSub

for i as integer = 1 to 10
sMessage = i.tostring ' This works because i is local to the for
loop
next i

sMessage = "Final 'i' is " & i.toString ' This will fail because
i isn't available outside the for loop
End Sub

Mike Ober.
"YGeek" <YG***@discussions.microsoft.com> wrote in message
news:0C**********************************@microsof t.com...
Is there any difference between declaring a variable at the top of a method versus in the code of the method? Is there a performance impact for either choice? What about if the method will return before the variable is used?
I'm trying to get an idea of whether the .NET compilers for VB.NET and C#
will move all variable declaration to the beginning of a method or whether
they will allocate the memory as it is needed by the method to conserve
memory.

Example (VB.NET):
' Declaration at the top of a method.
Public Sub SampleSub()
Dim sMessage As String
' ... Other code that might exit the method early ...
sMessage = "Hello!"
End Sub

' Declaration in a method.
Public Sub SampleSub()
' ... Code that might exit the method early ...
Dim sMessage As String = "Hello!"
End Sub


Jul 21 '05 #2
I respectfully disagree with your assessment of where to put a Dim.

It is my opinion that you should put all your declarations at the top of a
sub in alphabetical order. I think it's just tidy programming. In general,
sub/functs shouldn't have very many variables anyway. If you find yourself
creating a huge list of variables, then you are not breaking your code down
into appropriate routines in my opinion.

Just a thought.
"AMercer" wrote:
1. In VB, I believe that Dim is an executable statement, whereas with C,
declarations have to be at the top of a block of code (ie at the top of a
{..} sequence). A modest performance improvement should exist for a VB
return preceding a dim. It could be significant if there are a lot of dim's
and/or big and complex initializers.

2. I think it is a good idea to locate a dim statement in conjunction with
its usage/scope with a sub. If a variable is used throughout a sub, then dim
it at the top of the sub. If it is used in a small area of a relatively
large sub, then dim it near where it is used. If you dim within an if-then
block (for example), you do limit the scope of the variable. The following
sub will compile ok:
Private Sub x()
Dim Something as boolean
If Something Then
Dim b As integer
End If
' b=0 ' under option strict, this will not compile because b is not
declared
End Sub
Above, the scope of 'b' is the 'then' block.

3. Continuing the above example (both Basic and C), if boolean SomeThing is
false, the 'then' block will not execute, and that includes dim'ing 'b'. If
there are many dim statements with initializers, the performance change may
be significant.

"YGeek" wrote:
Is there any difference between declaring a variable at the top of a method
versus in the code of the method? Is there a performance impact for either
choice? What about if the method will return before the variable is used?
I'm trying to get an idea of whether the .NET compilers for VB.NET and C#
will move all variable declaration to the beginning of a method or whether
they will allocate the memory as it is needed by the method to conserve
memory.

Example (VB.NET):
' Declaration at the top of a method.
Public Sub SampleSub()
Dim sMessage As String
' ... Other code that might exit the method early ...
sMessage = "Hello!"
End Sub

' Declaration in a method.
Public Sub SampleSub()
' ... Code that might exit the method early ...
Dim sMessage As String = "Hello!"
End Sub

Jul 21 '05 #3
Shawn Brock <Sh********@discussions.microsoft.com> wrote:
I respectfully disagree with your assessment of where to put a Dim.

It is my opinion that you should put all your declarations at the top of a
sub in alphabetical order. I think it's just tidy programming. In general,
sub/functs shouldn't have very many variables anyway. If you find yourself
creating a huge list of variables, then you are not breaking your code down
into appropriate routines in my opinion.


No, it's not tidy programming IMO. It's bunching unrelated stuff
together. Keeping it as close to the first usage, within the tightest
scope possible keeps it tidier. It also helps you to make sure you
don't accidentally use an "old" value later on in the method where you
*really* wanted a new variable.

Also, putting them in alphabetical order removes the information about
which variables are related.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Jul 21 '05 #4
1. In VB, I believe that Dim is an executable statement, whereas with C,
declarations have to be at the top of a block of code (ie at the top of a
{..} sequence). A modest performance improvement should exist for a VB
return preceding a dim. It could be significant if there are a lot of dim's
and/or big and complex initializers.

2. I think it is a good idea to locate a dim statement in conjunction with
its usage/scope with a sub. If a variable is used throughout a sub, then dim
it at the top of the sub. If it is used in a small area of a relatively
large sub, then dim it near where it is used. If you dim within an if-then
block (for example), you do limit the scope of the variable. The following
sub will compile ok:
Private Sub x()
Dim Something as boolean
If Something Then
Dim b As integer
End If
' b=0 ' under option strict, this will not compile because b is not
declared
End Sub
Above, the scope of 'b' is the 'then' block.

3. Continuing the above example (both Basic and C), if boolean SomeThing is
false, the 'then' block will not execute, and that includes dim'ing 'b'. If
there are many dim statements with initializers, the performance change may
be significant.

"YGeek" wrote:
Is there any difference between declaring a variable at the top of a method
versus in the code of the method? Is there a performance impact for either
choice? What about if the method will return before the variable is used?
I'm trying to get an idea of whether the .NET compilers for VB.NET and C#
will move all variable declaration to the beginning of a method or whether
they will allocate the memory as it is needed by the method to conserve
memory.

Example (VB.NET):
' Declaration at the top of a method.
Public Sub SampleSub()
Dim sMessage As String
' ... Other code that might exit the method early ...
sMessage = "Hello!"
End Sub

' Declaration in a method.
Public Sub SampleSub()
' ... Code that might exit the method early ...
Dim sMessage As String = "Hello!"
End Sub

Jul 21 '05 #5
Alphabetical doesn't make much sense to me. With i and j for for-loops and
interval for something else, there is no good reason to replace 'dim i, j as
integer' with dim i, then dim interval, and then dim j. Also, if you use
initializers with your dim statements, then sometimes you have to order your
dim's so the initializers are well defined, eg
Dim sra As Reflection.Assembly = Reflection.Assembly.GetExecutingAssembly
Dim MyStream As IO.Stream = sra.GetManifestResourceStream("somename")
Dim Buffer(CInt(MyStream.Length)) As Byte
Here, MyStream depends on sra, Buffer depends on MyStream, Buffer is as big
as it needs to be, and the code is economical and understandable.

"Jon Skeet [C# MVP]" wrote:
Shawn Brock <Sh********@discussions.microsoft.com> wrote:
I respectfully disagree with your assessment of where to put a Dim.

It is my opinion that you should put all your declarations at the top of a
sub in alphabetical order. I think it's just tidy programming. In general,
sub/functs shouldn't have very many variables anyway. If you find yourself
creating a huge list of variables, then you are not breaking your code down
into appropriate routines in my opinion.


No, it's not tidy programming IMO. It's bunching unrelated stuff
together. Keeping it as close to the first usage, within the tightest
scope possible keeps it tidier. It also helps you to make sure you
don't accidentally use an "old" value later on in the method where you
*really* wanted a new variable.

Also, putting them in alphabetical order removes the information about
which variables are related.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Jul 21 '05 #6
I took a different understanding of the question. It's not the declaration
location that is changing in the example, but where it is assigned the value
"Hello!"

Does this make any difference?
"YGeek" <YG***@discussions.microsoft.com> wrote in message
news:0C**********************************@microsof t.com...
Is there any difference between declaring a variable at the top of a
method
versus in the code of the method? Is there a performance impact for
either
choice? What about if the method will return before the variable is used?
I'm trying to get an idea of whether the .NET compilers for VB.NET and C#
will move all variable declaration to the beginning of a method or whether
they will allocate the memory as it is needed by the method to conserve
memory.

Example (VB.NET):
' Declaration at the top of a method.
Public Sub SampleSub()
Dim sMessage As String
' ... Other code that might exit the method early ...
sMessage = "Hello!"
End Sub

' Declaration in a method.
Public Sub SampleSub()
' ... Code that might exit the method early ...
Dim sMessage As String = "Hello!"
End Sub

Jul 21 '05 #7
It's all about where the variable is declared, not where it is assigned.
The location that a variable is declared determines its "scope" or lifetime
or accesibility.

Here are ALL the VB.NET levels of scope:

The smallest scope there is in VB.NET is "Block Level Scope". A "block" of
code is anything that can be written in a procedure that has a beginning and
an end. For example, For...Next, If...End If, Try...End Try, Select...End
Select are all examples of blocks of code. Be careful though because a
block may contain smaller blocks inside of it:

If foo then
'this is a block
elseif foo then
'this is a different block
else
'this is a different block
end if

So, anything declared in a block is only accessible from within that block.
The variable pointer itself will stay in memory until the procedure ends.

Anything declared within a procedure, but not in a block with the word Dim
has "Procedure Level Scope" and is accessible from anywhere in the procedure
(including inside of blocks). The variable pointer itself will stay in
memory until the procedure ends.

Anything declared within a procedure with the keyword Static will is
accessible as if it was declared with Dim (in or out of a block) but with
the difference that the variable's value will not be lost when the variable
falls out of scope. If the program should re-enter the procedure, the
variable's last value will still be accesible.

Anything declared at the module level (not inside a procedure) with the
keyword Dim or Private is accessible from any procedure within the module.
The variable pointer itself will stay in memory until the module is removed
from memory.

Anything declared with the keyword Protected is accessible as if it was
declared Private at the module level with the exception that it is also
accessible from classes that derive from the class the the keyword was used
in.

Anything declared with Freind is accessible anywhere in the assembly that
the declaration appears in.

Anything declared with Public is accessible anywhere in the assembly as well
as outside the assembly.

Anything delcared as a Web Service is available from other machines via a
web reference.

Anything in a Web Service that is declared as a Web Method is available to
be called by the remote machine that has made an instance of the web service
class.

"JohnFol" <Ou************@WibbleObbble.Com> wrote in message
news:9Y******************@newsfe3-win.ntli.net...
I took a different understanding of the question. It's not the declaration
location that is changing in the example, but where it is assigned the
value "Hello!"

Does this make any difference?
"YGeek" <YG***@discussions.microsoft.com> wrote in message
news:0C**********************************@microsof t.com...
Is there any difference between declaring a variable at the top of a
method
versus in the code of the method? Is there a performance impact for
either
choice? What about if the method will return before the variable is
used?
I'm trying to get an idea of whether the .NET compilers for VB.NET and C#
will move all variable declaration to the beginning of a method or
whether
they will allocate the memory as it is needed by the method to conserve
memory.

Example (VB.NET):
' Declaration at the top of a method.
Public Sub SampleSub()
Dim sMessage As String
' ... Other code that might exit the method early ...
sMessage = "Hello!"
End Sub

' Declaration in a method.
Public Sub SampleSub()
' ... Code that might exit the method early ...
Dim sMessage As String = "Hello!"
End Sub


Jul 21 '05 #8

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

Similar topics

83
by: Alexander Zatvornitskiy | last post by:
Hello All! I'am novice in python, and I find one very bad thing (from my point of view) in language. There is no keyword or syntax to declare variable, like 'var' in Pascal, or special syntax in...
20
by: CoolPint | last post by:
While I was reading about const_cast, I got curious and wanted to know if I could modify a constant variable through a pointer which has been "const_cast"ed. Since the pointer would be pointing to...
134
by: James A. Donald | last post by:
I am contemplating getting into Python, which is used by engineers I admire - google and Bram Cohen, but was horrified to read "no variable or argument declarations are necessary." Surely that...
8
by: YGeek | last post by:
Is there any difference between declaring a variable at the top of a method versus in the code of the method? Is there a performance impact for either choice? What about if the method will return...
23
by: Russ Chinoy | last post by:
Hi, This may be a totally newbie question, but I'm stumped. If I have a function such as: function DoSomething(strVarName) { ..... }
3
by: Mark Berry | last post by:
Hi, I'm moving from VB6 to VB 2005. Two questions: 1. One book I'm using has syntax like Dim testConnection as SqlConnection = New SqlConnection(connectionString) However, the Help for...
7
by: gyan | last post by:
follwing code gives error: 1 #include<iostream.h> 2 int main() 3 { 4 int a=5,b; 5 switch(a){ 6 case 1: 7 {b=5; 8 break; 9 }
2
by: Shraddha | last post by:
Can we declare extern variable as static? What will be the scope of the variable then? What if we change the value of the variable in some other function? Also can someone tell me that if we can...
112
by: istillshine | last post by:
When I control if I print messages, I usually use a global variable "int silent". When I set "-silent" flag in my command line parameters, I set silent = 1 in my main.c. I have many functions...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
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: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
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
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,...

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.