472,374 Members | 1,523 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,374 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 2847
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,...
2
by: Kemmylinns12 | last post by:
Blockchain technology has emerged as a transformative force in the business world, offering unprecedented opportunities for innovation and efficiency. While initially associated with cryptocurrencies...
0
by: Naresh1 | last post by:
What is WebLogic Admin Training? WebLogic Admin Training is a specialized program designed to equip individuals with the skills and knowledge required to effectively administer and manage Oracle...
0
by: antdb | last post by:
Ⅰ. Advantage of AntDB: hyper-convergence + streaming processing engine In the overall architecture, a new "hyper-convergence" concept was proposed, which integrated multiple engines and...
0
hi
by: WisdomUfot | last post by:
It's an interesting question you've got about how Gmail hides the HTTP referrer when a link in an email is clicked. While I don't have the specific technical details, Gmail likely implements measures...
1
by: Matthew3360 | last post by:
Hi, I have been trying to connect to a local host using php curl. But I am finding it hard to do this. I am doing the curl get request from my web server and have made sure to enable curl. I get a...
0
by: Carina712 | last post by:
Setting background colors for Excel documents can help to improve the visual appeal of the document and make it easier to read and understand. Background colors can be used to highlight important...
0
BLUEPANDA
by: BLUEPANDA | last post by:
At BluePanda Dev, we're passionate about building high-quality software and sharing our knowledge with the community. That's why we've created a SaaS starter kit that's not only easy to use but also...
1
by: Johno34 | last post by:
I have this click event on my form. It speaks to a Datasheet Subform Private Sub Command260_Click() Dim r As DAO.Recordset Set r = Form_frmABCD.Form.RecordsetClone r.MoveFirst Do If...
0
by: jack2019x | last post by:
hello, Is there code or static lib for hook swapchain present? I wanna hook dxgi swapchain present for dx11 and dx9.

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.