Getting access to the array’s elements allocated on stack

1. Which arrays we can access using unsafe array access technique?

2. Which type of arrays is possible to allocate on the thread’s stack.

3. Accessing to an array using the stackalloc function.

4. Accessing to an array using inline arrays.

5. Requirements to inline arrays.

6. When unsafe allocated memory will be freed.

Unsafe array access is very powerful feature because it allows to access to elements that reside:

1.    on the managed heap.

2.    on an unmanaged heap

3.    on the thread’s stack

If we concern about performance we can allocate array on thread’s stack and it is possible only for single-dimension zero-based arrays of value type elements only.  

 

Example 1. Stackalloc function.

 

class Program

{

    private const string _strTests = "Tests";

    private const int _length = 5;

 

    public static void Main()

    {

        StackAllocReverseString(_strTests);

        InlineArrayReverseString(_strTests);

    }

 

    private static void StackAllocReverseString(string str)

    {

        unsafe

        {

            char* pStr = stackalloc char[_length];

 

            for (int i = 0; i < _length; i++)

            {

                pStr[_length – i – 1] = str[i];

            }

 

            Console.WriteLine(new String(pStr));

        }

    }

 

Example 2. Inline array.

 

    private unsafe struct CharactersArray

    {

        public fixed char Characters[_length];

    }

 

    private static void InlineArrayReverseString(string str)

    {

        unsafe

        {

            CharactersArray pStr;

            for (int i = 0; i < _length; i++)

            {

                pStr.Characters[_length – i – 1] = str[i];

            }

 

            Console.WriteLine(new String(pStr.Characters));

        }

    }

}

In case of an inline array the type which will be allocated on stack must have following properties:

1.     It must be value type only (struct)

2.     The structure must be marked with the unsafe keyword.

3.     The array must be marked with the fixed keyword.

4.     The array must be single dimensioned zero based.

5.      Types of elements which can be reside on the array must be following types: bool, byte, sbyte, int, uint, long, ulong, char, float, double.

 

Of course, a stack allocated memory will automatically be freed when a method returns, this is when we get the performance improvement.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s