Game Development Reference
In-Depth Information
Note
Stackalloc is very similar to the _alloca method in the C runtime library. Stackalloc depends
on the use of pointers, so you can only use it within an unsafe context.
The memory is only allocated by stackalloc , so initialization is up to you. One
common usage for stackalloc in terms of performance is when dealing with
arrays. The .NET platform provides excellent mechanisms for dealing with arrays,
but the data are still objects instantiated from System.Array and stored on the heap,
so all the related overhead is incurred when dealing with them.
You can allocate enough memory to store 10 integers with the following code.
int* intArray = stackalloc int[10];
There are a couple of ways to access the array members.
You can use *(intArray + i) , where i is the index of the array element to access.
*(intArray + 0) = 123;
*(intArray + 1) = 456;
*(intArray + 2) = 789;
You can also use intArray[i] to access the array elements.
intArray[0] = 123;
intArray[1] = 456;
intArray[2] = 789;
Normally, when you access a member outside of the array bounds, an out of
bounds exception will be thrown. When using stackalloc , however, you are access-
ing an address located somewhere on the stack. Writing to an incorrect address
could corrupt a variable, or even return an address from a method currently being
executed.
For example:
int* intArray = stackalloc int[5];
intArray[7] = 123; // This means that (intArray + 7 * sizeof(int)) had
// a value of 123 assigned to it.
Caution
The moral of the story is, be very careful!
 
Search Nedrilad ::




Custom Search