Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 925227
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 15, 20262026-05-15T19:29:14+00:00 2026-05-15T19:29:14+00:00

Is it better to declare a variable used in a loop outside of the

  • 0

Is it better to declare a variable used in a loop outside of the loop rather then inside? Sometimes I see examples where a variable is declared inside the loop. Does this effectively cause the program to allocate memory for a new variable each time the loop runs? Or is .NET smart enough to know that it’s really the same variable.

For example see the code below from this answer.

public static void CopyStream(Stream input, Stream output)
{
    byte[] buffer = new byte[32768];
    while (true)
    {
        int read = input.Read (buffer, 0, buffer.Length);
        if (read <= 0)
            return;
        output.Write (buffer, 0, read);
    }
}

Would this modified version be any more efficent?

public static void CopyStream(Stream input, Stream output)
{
    int read; //OUTSIDE LOOP
    byte[] buffer = new byte[32768];
    while (true)
    {
        read = input.Read (buffer, 0, buffer.Length);
        if (read <= 0)
            return;
        output.Write (buffer, 0, read);
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-15T19:29:15+00:00Added an answer on May 15, 2026 at 7:29 pm

    No, it wouldn’t be more efficient. However, I’d rewrite it this way which happens to declare it outside the loop anyway:

    byte[] buffer = new byte[32768];
    int read;
    while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
    {
        output.Write(buffer, 0, read);
    }
    

    I’m not generally a fan of using side-effects in conditions, but effectively the Read method is giving you two bits of data: whether or not you’ve reached the end of the stream, and how much you’ve read. The while loop is now saying, “While we’ve managed to read some data… copy it.”

    It’s a little bit like using int.TryParse:

    if (int.TryParse(text, out value))
    {
        // Use value
    }
    

    Again you’re using a side-effect of calling the method in the condition. As I say, I don’t make a habit out of doing this except for this particular pattern, when you’re dealing with a method returning two bits of data.

    The same thing comes up reading lines from a TextReader:

    string line;
    while ((line = reader.ReadLine()) != null)
    {
        ...
    }
    

    To go back to your original question: if a variable is going to be initialized in every iteration of a loop and it’s only used within the body of the loop, I’d almost always declare it within the loop. One minor exception here is if the variable is being captured by an anonymous function – at that point it will make a difference in behaviour, and I’d pick whichever form gave me the desired behaviour… but that’s almost always the “declare inside” form anyway.

    EDIT: When it comes to scoping, the code above does indeed leave the variable in a larger scope than it needs to be… but I believe it makes the loop clearer. You can always address this by introducing a new scope if you care to:

    {
        int read;
        while (...)
        {
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Is there a better way to flash a window in Java than this: public
What would be better practice when giving a function the original variable to work
In case I have a variable that may be used in several sources -
I'm used to creating sounds like this: NSString *explosionsoundpath = [[NSBundle mainBundle] pathForResource:@explosion ofType:@caf];
Does anyone have any idea of why this could happen? I have a C
Many Java frameworks allow class members used for injection to be declared non-public. For
public bool PrepaymentCalculating { get; set; } So I declare a variable on one
Better yet, how can I make My Computer always open in Explorer as well?
Or better said: When to use array as a field data type in a
Even better would be if autoResize in latest branch would work as intended, but

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.