2

Suppose you have this code:

static void Send(byte[] buffer, int offset, int count)
{
    while (count > 0)
    {
        int size = sock.Send(buffer, offset, count);

        if (size == 0) throw new EndOfStreamException();

        offset += size;
        count -= size;
    }
}

vs.

static void Send(byte[] buffer, int offset, int count)
{
    int size;

    while (count > 0)
    {
        size = sock.Send(buffer, offset, count);

        if (size == 0) throw new EndOfStreamException();

        offset += size;
        count -= size;
    }
}

My teacher told me the second one would be more efficient, but is that true?

I did some testing and compared the assembly code and it was equal.

But will this always be the case?

  • What if instead of a primitive type you used a reference type? (assuming you don't allocate)
  • What about using multiple variables?
  • Will there ever be differences between the two possibilities?

Thanks in advance for any answers, I apologize if this has been asked before but I didn't really know how to call it.

too honest for this site
  • 12,050
  • 4
  • 30
  • 52
hl3mukkel
  • 5,369
  • 3
  • 21
  • 21

1 Answers1

1

Depends on the compiler optimizations - but since it's the same scope (function) - implementation would (usually) be the same.

As long as you don't instantiate anything new in that row, it's a local variable in the function scope.

Raz Abramov
  • 181
  • 12