Is it better to instantiate a variable for each instance or outside the loop?
If it matters why.

a) Each instance
for(int i=0;i<30;i++){
   int itemId=.....;
b) outside the loop:
int itemId=0;
for(int i=0;i<30;i++){
Who is Participating?
Fernando SotoConnect With a Mentor RetiredCommented:
To the question, "Is it better to instantiate a variable for each instance or outside the loop?", It is just a matter of personal style. The only benefit by using option "B" above is that you have access to the loop control variable outside of the loop if you need it.
HooKooDooKuConnect With a Mentor Commented:
Here is my best GUESS (based on my experience with programming, working with complilers, and what I know about assymbly language)...

It doesn't matter apart from scope (i.e. where the variable can be seen/accessed).
The only way it COULD make a difference at runtime is if the variable keeps getting initialized each time the loop is run.  For languages such as VB that ALWAYS initialize a variable for you, each time through the loop would be running extra code to reset the variable value.  But for languages such as C, a variable such as this is created by simply allocating space on the stack at the start of the function.  The initial value of the variable is what ever random data was at that memory location when allocated.  The variable exists during the entire execution of the function, but the compliler limits access to the variable to within the loop.
anarki_jimbelConnect With a Mentor Commented:
I agree to FernandoSoto - this is a matter of style mainly. However, there are some recommendations:
Variables should be declared as close to where they are used as possible.

In your case - inside the loop (unless you need this variable outside the loop).

See the discussion:
Anurag ThakurConnect With a Mentor Technical ManagerCommented:
in case of a int or a value type variable declaration and initialization will make much difference for a large object/reference type variables
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.