The stackalloc keyword
C# has the stackalloc keyword which lets you force unmanaged type arrays to be allocated on the stack inside unsafe contexts:
int* ptr = stackalloc int[1024];
This will allocate a contiguous array of 1024 integers on the stack. Similarly, you can allocate an array of unmanaged structs on the stack as well:
TestStruct1* ptr2 = stackalloc TestStruct1[10];
This type of allocation is really fast, the garbage collector is never invoked and transversing the array has greatly reduced overhead. This is can be a huge win for performance minded applications. There is one big disadvantage that should be kept in mind however: because things allocated on the stack will go away when they go out of context, they must be copied if you want to use their contents outside of the current method.
The only case in which memory is bounds checked in unsafe code is with stackalloced memory. This constant checking does not come for free and so you may see even better performance when using the fixed keyword inside a stack allocated struct.
The fixed Keyword
.NET 2.0 and later have a keyword called fixed for defining fixed length arrays as part of a struct in unsafe contexts. Unlike using dynamic array allocation, a fixed length array will be considered as part of the struct instead of just a reference. It also has the added bonus of being an unmanaged type and so a struct which uses it will be stack allocated by default.
struct TestStructFixed
{
{
public int i;
public fixed int k[1024];
public fixed int k[1024];
}
TestStructFixed tsf = new TestStructFixed();
It is very important to note that arrays defined with the fixed keyword will do no bounds checking for you.
No comments:
Post a Comment