473,847 Members | 2,426 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Declaring variables and performance

I have a MSIL/performance question:

Is there any difference between declaring a variable once and assigning
to it multiple times, and declaring and assigning multiple times?

For example:

// Begin sample
for(int i = 0; i < 100; i++)
{
StringBuilder sb = new StringBuilder() ;
...
}
// End sample

as opposed to

// Begin sample
StringBuilder sb;

for(int i = 0; i < 100; i++)
{
sb = new StringBuilder() ;
}
// End sample

Are those basically the same, or is there a performance advantage to
the second (or indeed first) method?

Cheers,
Mark

Jun 27 '06 #1
8 5868
Hi Mark,

If you're only using the StrinbBuilder inside the loop, then I'd
declare it inside the loop block so it is scoped to this - which is
good practice. If there is any performance difference it's going to be
very very marginal and totally negligible.

Worrying about this is definitely a case of premature optimisation
(http://www.thejoyofcode.com/Premature_Optimisation.aspx) and possibly
trying too hard too soon
(http://www.thejoyofcode.com/Trying_t...too_soon.aspx)...

:D

Good luck!

Josh

re****@gmail.co m wrote:
I have a MSIL/performance question:

Is there any difference between declaring a variable once and assigning
to it multiple times, and declaring and assigning multiple times?

For example:

// Begin sample
for(int i = 0; i < 100; i++)
{
StringBuilder sb = new StringBuilder() ;
...
}
// End sample

as opposed to

// Begin sample
StringBuilder sb;

for(int i = 0; i < 100; i++)
{
sb = new StringBuilder() ;
}
// End sample

Are those basically the same, or is there a performance advantage to
the second (or indeed first) method?

Cheers,
Mark


Jun 27 '06 #2
Hi Josh

Thanks. I'm not really trying to optimise the code; just curiosity,
really. I recently got "CLR via C#", and may be suffering from
too-much-information syndrome.

Liked the articles you linked. I've definitely been guilty of premature
optimisation in the past.

Mark

Josh Twist wrote:
Hi Mark,

If you're only using the StrinbBuilder inside the loop, then I'd
declare it inside the loop block so it is scoped to this - which is
good practice. If there is any performance difference it's going to be
very very marginal and totally negligible.

Worrying about this is definitely a case of premature optimisation
(http://www.thejoyofcode.com/Premature_Optimisation.aspx) and possibly
trying too hard too soon
(http://www.thejoyofcode.com/Trying_t...too_soon.aspx)...

:D

Good luck!

Josh


Jun 27 '06 #3
Hi,

They should be the same (performance wise). The only difference is in scope.

Now a better question would had been, what is better , create a new instance
each time or instead use sb.Length = 0 ;

I got a similar situation yesterday but I had no time to decide which is the
"best" way to go ( I used Length=0 )
--
--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation

<re****@gmail.c om> wrote in message
news:11******** **************@ p79g2000cwp.goo glegroups.com.. .
I have a MSIL/performance question:

Is there any difference between declaring a variable once and assigning
to it multiple times, and declaring and assigning multiple times?

For example:

// Begin sample
for(int i = 0; i < 100; i++)
{
StringBuilder sb = new StringBuilder() ;
...
}
// End sample

as opposed to

// Begin sample
StringBuilder sb;

for(int i = 0; i < 100; i++)
{
sb = new StringBuilder() ;
}
// End sample

Are those basically the same, or is there a performance advantage to
the second (or indeed first) method?

Cheers,
Mark

Jun 27 '06 #4
>I have a MSIL/performance question:

Is there any difference between declaring a variable once and assigning
to it multiple times, and declaring and assigning multiple times?


From an MSIL point of view it doesn't matter. In the compiled code the
variable "declaratio ns" come in the method header, before the IL code.
So where you put your declaration in your C# code doesn't matter.
Mattias

--
Mattias Sjögren [C# MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Jun 27 '06 #5
<"Ignacio Machin \( .NET/ C# MVP \)" <ignacio.mach in AT
dot.state.fl.us >> wrote:
They should be the same (performance wise). The only difference is in scope.

Now a better question would had been, what is better , create a new instance
each time or instead use sb.Length = 0 ;

I got a similar situation yesterday but I had no time to decide which is the
"best" way to go ( I used Length=0 )


I'd generally go with creating a new object - that way you're less
likely to end up with it getting into "old" generations which will then
be garbage collected later on.

Note that in C# 2.0, the difference in scope can affect behaviour if
the variable is used in an anonymous method.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Jun 27 '06 #6
As I suspected, I just tried a quick experiment and both compile to
exactly the same MSIL (the compiler recognises that the var isn't used
outside the block so moves its declaration inside).

I guess there is another factor to reinforce our decision to place it
inside the block though - readability. If I see a variable declared
inside a block I know it isn't used in anyway outside of that block.

Josh
http://www.thejoyofcode.com/

Jon wrote:
<"Ignacio Machin \( .NET/ C# MVP \)" <ignacio.mach in AT
dot.state.fl.us >> wrote:
They should be the same (performance wise). The only difference is in scope.

Now a better question would had been, what is better , create a new instance
each time or instead use sb.Length = 0 ;

I got a similar situation yesterday but I had no time to decide which is the
"best" way to go ( I used Length=0 )


I'd generally go with creating a new object - that way you're less
likely to end up with it getting into "old" generations which will then
be garbage collected later on.

Note that in C# 2.0, the difference in scope can affect behaviour if
the variable is used in an anonymous method.

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


Jun 28 '06 #7
Hi,
Good point.

One possible good side effect of reusing the previous one is that the new
string most likely is of similar size, so if the StringBuilder had to
increase the size it will not have to do that again.
--
--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation

"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
<"Ignacio Machin \( .NET/ C# MVP \)" <ignacio.mach in AT
dot.state.fl.us >> wrote:
They should be the same (performance wise). The only difference is in
scope.

Now a better question would had been, what is better , create a new
instance
each time or instead use sb.Length = 0 ;

I got a similar situation yesterday but I had no time to decide which is
the
"best" way to go ( I used Length=0 )


I'd generally go with creating a new object - that way you're less
likely to end up with it getting into "old" generations which will then
be garbage collected later on.

Note that in C# 2.0, the difference in scope can affect behaviour if
the variable is used in an anonymous method.

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

Jun 28 '06 #8
Thanks to everyone for the replies and info. I guess I really should
start looking at the MSIL myself.

Mark

Jun 30 '06 #9

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

Similar topics

2
2143
by: Oliver Corona | last post by:
I am wondering if anyone has any insights on the performance benefit (or detriment) of declaring local variables instead of referencing members. Is allocating memory for a new variable more efficient than repeatedly referencing the member in a loop? Maybe using a string isn't the best example, but hopefully you get the idea! * example (referencing member):
1
2440
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 program which control to requery. This makes it easy to requery controls on a different form. However, up until today, I was dimming a new local variable for each control I wanted to deal with ( E.G. Dim cbxctl as control) and then setting that...
115
7673
by: Mark Shelor | last post by:
I've encountered a troublesome inconsistency in the C-language Perl extension I've written for CPAN (Digest::SHA). The problem involves the use of a static array within a performance-critical transform function. When compiling under gcc on my big-endian PowerPC (Mac OS X), declaring this array as "static" DECREASES the transform throughput by around 5%. However, declaring it as "static" on gcc/Linux/Intel INCREASES the throughput by...
28
4657
by: Dennis | last post by:
I have a function which is called from a loop many times. In that function, I use three variables as counters and for other purposes. I can either use DIM for declaring the variables or Static. Would the performance be better using Static versus Dynamic. I would think it would be quicker with STATIC declarations since the variables would only have to be created once. Can anyone confirm this. Thanks. -- Dennis in Houston
6
3519
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 error saying to change Public to Dim. When I do, it will say that Test1 is an unused local variable.
3
2273
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() on WebForm1.aspx, I use "Public Property" and I declare variable _oRpte as Friend Shared. That's my problem. If I don't declare _oRpte as Friend Shared, I can't use WebForm1.oRpte() on other webpage. If I declare _oRpte as Friend Shared, I can use...
8
7527
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, like this: for(var i=0; i<list; i++) { var name = list; }
6
2989
by: =?Utf-8?B?QUw=?= | last post by:
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++) {
8
4599
by: nguillot | last post by:
Hello. If I have the following classes: class B {}; typedef B tB; if A is: class A
0
9879
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 usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9727
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10643
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10330
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9477
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7879
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7050
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5716
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
4113
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.