473,396 Members | 1,918 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,396 software developers and data experts.

Declaring variables in loops

Hi

I usually stick to the convention of not declaring variables in my bodies of
"loops" (including foreach)

ie

int x;

for (int i = 0; i < 10; i++) {
x = ...
}

as opposed to
for (int i = 0; i < 10; i++) {
int x = ...
}

I've heard that in Java declaring variables within loops can cause problems
and I've tried to create some metrics to compare the difference in C# code
between prior to the loop and within the loop.

My results indicated that there was no difference.

I'd like to get a better idea from any one else as to whether my conclusion
is acurate or there is some form of performance hit.

Thanks in advance

AL

May 23 '07 #1
6 2958
below is a smple of how i approach loops..im not a c# guru..but looping to
me crating a new class each time would be a preformance hit
versus create the class once and change its existing value....(no mem clean
up or construction of a new class)

int x=0;
int y=100;
int z=1000;

for (x=0;x<y;x++)
{
z+=x;
Console.WriteLine(z.ToString());
}
Console.ReadKey();

MJ

"AL" <AL@discussions.microsoft.comwrote in message
news:38**********************************@microsof t.com...
Hi

I usually stick to the convention of not declaring variables in my bodies
of
"loops" (including foreach)

ie

int x;

for (int i = 0; i < 10; i++) {
x = ...
}

as opposed to
for (int i = 0; i < 10; i++) {
int x = ...
}

I've heard that in Java declaring variables within loops can cause
problems
and I've tried to create some metrics to compare the difference in C# code
between prior to the loop and within the loop.

My results indicated that there was no difference.

I'd like to get a better idea from any one else as to whether my
conclusion
is acurate or there is some form of performance hit.

Thanks in advance

AL

May 23 '07 #2
>I'd like to get a better idea from any one else as to whether my conclusion
is acurate or there is some form of performance hit.
Performance wise there shouldn't be any difference (as long as you
don't also initialize the variable in the declaration).

Personally I prefer to declare the variable inside the loop, and in
general to keep the variable scope as narrow as possible. That
prevents me from accidentally using a variable after I'm done with it.
Mattias

--
Mattias Sjögren [C# MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
May 23 '07 #3
AL wrote:
Hi

I usually stick to the convention of not declaring variables in my bodies of
"loops" (including foreach)

ie

int x;

for (int i = 0; i < 10; i++) {
x = ...
}

as opposed to
for (int i = 0; i < 10; i++) {
int x = ...
}

I've heard that in Java declaring variables within loops can cause problems
and I've tried to create some metrics to compare the difference in C# code
between prior to the loop and within the loop.

My results indicated that there was no difference.

I'd like to get a better idea from any one else as to whether my conclusion
is acurate or there is some form of performance hit.

Thanks in advance
In such a simple scenario as this the IL that's generated is the same so
the performance should also be the same.
--
Tom Porterfield
May 23 '07 #4
AL <AL@discussions.microsoft.comwrote:
I usually stick to the convention of not declaring variables in my bodies of
"loops" (including foreach)

ie

int x;

for (int i = 0; i < 10; i++) {
x = ...
}

as opposed to
for (int i = 0; i < 10; i++) {
int x = ...
}
No, the latter is generally nicer - it avoids "polluting" the namespace
of available variables, and shows that you genuinely intend to only use
the variable within the loop.
I've heard that in Java declaring variables within loops can cause problems
Until I see any evidence of of it, I'd be very sceptical of that.
Certainly in the all the time I've written Java, I've never run into
any issues like that.
and I've tried to create some metrics to compare the difference in C# code
between prior to the loop and within the loop.

My results indicated that there was no difference.

I'd like to get a better idea from any one else as to whether my conclusion
is acurate or there is some form of performance hit.
No, there isn't a performance hit unless you're able to initialize the
variable once and then leave it initialized to the same value. Even
then I'd take the readability improvement of the latter style over the
*possible* slight performance improvement of the former until I'd
proved it was a bottleneck.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
May 23 '07 #5
Mike J <ve***********@sbcglobal.netwrote:
below is a smple of how i approach loops..im not a c# guru..but looping to
me crating a new class each time would be a preformance hit
versus create the class once and change its existing value....(no mem clean
up or construction of a new class)

int x=0;
int y=100;
int z=1000;

for (x=0;x<y;x++)
{
z+=x;
Console.WriteLine(z.ToString());
}
Console.ReadKey();
Other than z.ToString() which is called on every iteration of the loop,
where do you see objects being created in the above? It's much neater
IMO to do

// These need to be outside the loop anyway
int y = 100;
int z = 1000;

for (int x=0; x < y; x++)
{
z += x;
Console.WriteLine(z.ToString());
}

Bottom line - don't trust instinct about performance without proof,
especially if it affects readability. (In your code it isn't clear that
x is only interesting within the loop - in my code it is.)

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
May 23 '07 #6
Hi,

"Mike J" <ve***********@sbcglobal.netwrote in message
news:vC****************@newssvr19.news.prodigy.net ...
below is a smple of how i approach loops..im not a c# guru..but looping to
me crating a new class each time would be a preformance hit
versus create the class once and change its existing value....(no mem
clean up or construction of a new class)
I do not understand your example.

Declaring a new instance inside the loop sometime makes sense, some other
times it does not.

if it's a valued type you incurr in no memory overhead at all. (see other;s
post in this thread). With a reference type it might have an impact.
May 23 '07 #7

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

Similar topics

3
by: sarmin kho | last post by:
Hi Pythoners, i have been using a lot of global variables in the python script i am working on. the global variables are shared and used by all various 'definitions' : def name (): global all...
3
by: Grey Plastic | last post by:
I'm looking for a way to declare variables inside for statements (or perhaps some other statement) and have the following statement execute exactly once. For example, for(Type var=blah; 1; ) ...
28
by: Alf P. Steinbach | last post by:
A few days ago I posted an "Hello, world!" tutorial, discussed in <url: http://groups.google.no/groups?threadm=41ba4c0a.76869078@news.individual.net>. As I wrote then: <quote> because there...
1
by: ColinWard | last post by:
Hi guys. I have a question about declaring variables. I do a lot of re-querying of controls in my database and I use the Set statement with a variable set to the name of the control to tell the...
9
by: Javaman59 | last post by:
Using local declarations within a block often makes code more readable, but is it less efficient? eg... void P() { while (...) { int i = ...; bool b = ...; .... } }
6
by: Mark A. Sam | last post by:
Hello, I am using Visual Web Developer 2005 Express. I want to declare a varible, using Visual Basic as the language and can't get anywhere. For example Public Test1 as String I'll get en...
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()...
10
by: PJackson | last post by:
Trying to declare a simple handler for SQLEXCEPTION. Simple stored proc (UDB 8.2) ---- CREATE PROCEDURE TFBUDB.SMACF_SM_DI (IN POL_NBR CHAR(10) , OUT ErrNo INTEGER , OUT ErrMsg CHAR(80) )...
8
by: SM | last post by:
I've always wonder if there is diference when declaring and initializing a varible inside/outside a loop. What's a better practice? Declaring and initializing variables inside a loop routine,...
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...
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
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
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
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...
0
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...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

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.