Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

Is it better to declare a variable outside of a loop, or does it not matter (performance wise)??

 

int start = 0;
int end = size - 1;            

while (start <= end)
{
   // Put it here or outside the block??
   int middle = (start + end) / 2;
   ....
}

"For every complex problem, there is a solution that is simple, neat, and wrong." - H. L. Mencken
  • Administrators
Posted
Performance wise it should make very little difference, from a code point of view though if the variable is only used within the block then declaring it within the block makes the code's intention that bit clearer and allows the compiler to enforce the variable scope.

Posting Guidelines FAQ Post Formatting

 

Intellectuals solve problems; geniuses prevent them.

-- Albert Einstein

Posted
I would say that any change in performance is negligable, if it's even there. The variable will still live until the procedure ends no matter where you declare it. It doesn't die once you leave the block, and it'll still have the same value if you reenter it.
Posted
I thought that space is made on the stack for the variable each time the block is entered. So, basically the variable just has scope in the block, but the variable is created once the procedure is called (Is that right)?
"For every complex problem, there is a solution that is simple, neat, and wrong." - H. L. Mencken

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...