InlineArray
Sometimes methods in complex C# programs require a small local array to store values. And when the method exits, the buffer array is no longer needed.
With the InlineArray
attribute, we can optimize performance of these methods—we can avoid slow allocations upon the garbage-collected heap. The array can be used in a similar way to other arrays.
This program uses the InlineArray
attribute and then accesses the memory within the Main
method. It writes and then reads from the elements.
InlineArray
with the new keyword. This is a struct
, so it is a value type.InlineArray
. We use the constant length 8, as the Length
property is not available.InlineArray
. We see that the values we stored are corrected loaded.[System.Runtime.CompilerServices.InlineArray(8)] struct Test { private int _element; } class Program { public static void Main() { // Step 1: create new InlineArray. var test = new Test(); // Step 2: assign each element in the InlineArray. for (int i = 0; i < 8; i++) { test[i] = i * 100; } // Step 3: print out values within the InlineArray. for (int i = 0; i < 8; i++) { System.Console.WriteLine(test[i]); } } }0 100 200 300 400 500 600 700
The entire point of the InlineArray
is to optimize performance, mostly for .NET methods. The InlineArray
should help by reducing allocations on the managed heap.
InlineArray
. We create it, write values to it, and then read the first element.for
-loop.InlineArray
had better performance in this particular benchmark. It could help speed up some methods that need buffers.InlineArray
is faster, but for larger ones (over 20) it tends to hurt performance.#define VERSION1 using System; using System.Diagnostics; [System.Runtime.CompilerServices.InlineArray(10)] struct Test { private int _element; } class Program { public static void Main() { const int _max = 10000000; var s1 = Stopwatch.StartNew(); for (int i = 0; i < _max; i++) { #if VERSION1 var test = new Test(); for (int x = 0; x < 10; x++) { test[x] = 5; } if (test[0] == -1) { return; } #endif #if VERSION2 var test = new int[10]; for (int x = 0; x < test.Length; x++) { test[x] = 5; } if (test[0] == -1) { return; } #endif } s1.Stop(); Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns")); } }2.76 ns InlineArray 5.55 ns int[50]
By providing a small buffers for methods, the InlineArray
can help speed up some programs. More importantly, it can be used to optimize the .NET standard library itself.