473,581 Members | 2,233 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 2658
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***@discussi ons.microsoft.c om> wrote in message
news:0C******** *************** ***********@mic rosoft.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********@dis cussions.micros oft.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.co m>
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.Asse mbly = Reflection.Asse mbly.GetExecuti ngAssembly
Dim MyStream As IO.Stream = sra.GetManifest ResourceStream( "somename")
Dim Buffer(CInt(MyS tream.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********@dis cussions.micros oft.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.co m>
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***@discussi ons.microsoft.c om> wrote in message
news:0C******** *************** ***********@mic rosoft.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.C om> wrote in message
news:9Y******** **********@news fe3-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***@discussi ons.microsoft.c om> wrote in message
news:0C******** *************** ***********@mic rosoft.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
6459
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 C. It can cause very ugly errors,like this: epsilon=0 S=0 while epsilon<10: S=S+epsilon
20
2062
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 the constant variable and if I changed the value through the pointer, the constant variable should have been modified. Well, that's what I thought...
134
7827
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 means that if I misspell a variable name, my program will mysteriously fail to work with no error message. If you don't declare variables, you...
8
359
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 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...
23
19155
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
1559
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 the Dim statement says, "If you use New, you do not
7
25130
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
4696
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 declare the global variable...and it is having scope throughout the file then what is so different in extern variable???
112
5391
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 that may print some messages. foo(...) { if (!silent)
0
7868
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7792
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8149
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8304
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7899
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
3827
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2301
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1403
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1138
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.