Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Question: Declaring variables in or out of the loop...

Status
Not open for further replies.

MissouriTiger

Programmer
Oct 10, 2000
185
US
This may be a stupid question, but I haven't been able to find an absolute answer.

In VB.NET (or any other language for that matter).

Suppose the follwing:

1. I am writing an application where speed is important.

2. In this application I am writing a function with a lot of variables, let's say at least 30 variables of type string, and 2 or 3 string arrays. This function is 400 lines long (including white space).

2. Most of these variables are going to be used inside of a loop, and the loop is going to repeat 10,000 times. With each iteration, the variables will be refreshed and used again. None of the data is reused in the next repetition of the loop. The data will be new each repetition. This loop is 200 lines long (including white space).

My question is this:

I have been declaring all of these variables outside of the loop, becuase I believed that creating a new variable each time the loop iterates would slow processing. Of course, this makes the code less easy to understand, since this is a huge function. But I am wondering if this really makes a difference.

Does it really matter whether the variables are created once, or if they are created every loop repetition?

Any thoughts or links to informative articles would be greatly appreciated.





Greg Norris
Software Developer & all around swell guy


__________________________________________________
Constructed from 100% recycled electrons.
 
I would assume that performance would be better when you instance the variables out of the loop, and assign values in the loop. But to make sure, you can use Environment.GetTicks() to determine the total number of cycles the computer has to go through to do the work. Store the number of ticks at the beginning of the method, and compare that value to the number of ticks at the end of the method.

-Rick

VB.Net Forum forum796 forum855 ASP.NET Forum
[monkey]I believe in killer coding ninja monkeys.[monkey]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top