0

I have the following method to copy bytes from a socket stream to disk:

 public static void CopyStream(Stream input, Stream output)
 {
    // Insert null checking here for production
    byte[] buffer = new byte[8192];
    int bytesRead;
    while ((bytesRead = input.Read(buffer, 0, buffer.Length)) > 0)
    {
        output.Write(buffer, 0, bytesRead);
    }
}

What I am curious about is: will buffer be allocated on the stack or on the heap? To be sure, I could make this method unsafe, and add the fixed keyword to the variable declaration, but I don't want to do that ifn I don't have to.

trincot
  • 317,000
  • 35
  • 244
  • 286
Jacko
  • 12,665
  • 18
  • 75
  • 126
  • 2
    pretty sure it's allocated from the heap but why would you care? The GC won't whack the memory if there's a reference to it... – seand May 19 '11 at 02:30
  • 1
    If you want it allocated on the stack, I fail to see how "fixed" will help you. Surely if you want it allocated on the stack, the aptly named "stackalloc" keyword is the one you want, not "fixed". That said, why on earth would you want this allocated on the stack? Is there something about a dangerous movement of the stack register by 8K that you feel is better than a safe movement of the managed heap high water mark by 8K? – Eric Lippert May 19 '11 at 06:48
  • 2
    Moreover: are you worried about the performance of the allocation? You're worried about the couple of nanoseconds it'll take to do the allocation, and not worried about the thousands or millions of nanoseconds its going to take to spin that enormous iron disk that you're writing onto into the correct position? It doesn't make any sense to optimize the nanoseconds while you're burning the milliseconds. – Eric Lippert May 19 '11 at 07:21

1 Answers1

4

The buffer variable will be allocated on the stack, the 8192 byte memory the buffer variable holds the location of will be on the heap.

why are you talking about fixed? Are you trying to speed things up? It almost certainly won't...

To quote Eric Lippert:

"But in the vast majority of programs out there, local variable allocations and deallocations are not going to be the performance bottleneck. "

Ref.

Mitch Wheat
  • 295,962
  • 43
  • 465
  • 541
  • 1
    totally agree with you. Measure first so you know what and where to optimize. often it spends a lot of time blocked in an I/O call. – Mel May 19 '11 at 02:42
  • Truth of authority, versus the authority of truth. You need to do a test to find out the truth. – nim Nov 22 '20 at 20:32