C# arrays

  • Thread starter Thread starter Neil Zanella
  • Start date Start date
N

Neil Zanella

Hello,

It seems that in C# arrays are always created on the heap. This seems
like it could prove somewhat inefficient in some situations. I would
like to know whether it is possible to create an array on the stack
in C# as it is possible in C and C++.

Thanks,

Neil
 
Neil Zanella said:
Hello,

It seems that in C# arrays are always created on the heap. This seems
like it could prove somewhat inefficient in some situations. I would
like to know whether it is possible to create an array on the stack
in C# as it is possible in C and C++.

It is not possible to allocate an array itself on the stack. However, when
using unsafe code you can generate a local buffer on the stack using a
rarely used keyword, stackalloc to return a pointer to that memory block.
 
Neil said:
Hello,

It seems that in C# arrays are always created on the heap. This seems
like it could prove somewhat inefficient in some situations. I would
like to know whether it is possible to create an array on the stack
in C# as it is possible in C and C++.

For now, you could try writing:

T[] Tarray = { t1, t2, ... };
f(Tarray);

And see if that hurts your performance too much... if it does, you'll
have to start doing something, but I think almost all things you could
try would slow things down more that it would speed them up.

The above way of writing has the nice effect of stating that you are
thinking of the array as being on the stack.

If the compiler grows clever enough and knows enough about the
side-effects of called functions, it might one day decide to allocate
that array on the stack.
 
Back
Top