Take the 2-minute tour ×

The .NET function Stream.Read() takes a byte[] as a parameter. Is there a way I can pass a stackalloc'd byte* instead? This would save me from having to make an extra heap allocation and in turn save time in garbage collection. This function is short and is repeatedly invoked.

share|improve this question
Suggestion: don't pre-optimize. What makes you think there's a significant performance penalty for using new byte[n]? –  John Saunders Jun 26 '11 at 0:18
No. Reuse the array instead. <!> –  Mehrdad Jun 26 '11 at 0:49
Because the garbage collector has to spend resources to check on it and eventually free it. This is why stackalloc was created in the first place. I'm working on an audio library that deals with samples of sound. For CD audio, there are 44,100 of them each second. This routine is going to be called quite a lot. –  wswartzendruber Jun 26 '11 at 1:37
Make it work correctly before you make it work faster. Otherwise you're in danger of have some very fast broken code. –  John Saunders Jun 26 '11 at 3:13
I was thinking of of sharing a single buffer for several different functions to use as a sandbox. Thanks to [ThreadStatic], I believe I can. –  wswartzendruber Jun 26 '11 at 4:32

2 Answers 2

up vote 2 down vote accepted

No you can't. You need to create an array and copy it into there first. See also this thread on MSDN forums.

Apart from that: I don't know the context of your application but maybe you can use a statically allocated buffer? In a multi threaded context you could allocate the buffer in the TLS like this:

class SomeDataProcessor
    static byte[] _Buffer;

Note that you need to be careful with initializers though. See also here

share|improve this answer
Whoa, I think we have a winner! –  wswartzendruber Jun 26 '11 at 1:38

I dont believe you can, but if you want to simplify the conversion. You can use:


Takes in a unmanaged address, size, byte buffer, etc

share|improve this answer

Your Answer


