A great example is described in J.Richter's "CLR via C #", 3 edition, Ch. 16: The following C # code demonstrates three methods (safe, jagged, and unsafe) to access a two-dimensional array:
using System; using System.Diagnostics; public static class Program { private const Int32 c_numElements = 10000; public static void Main() { const Int32 testCount = 10; Stopwatch sw;
The Unsafe2DimArrayAccess method is marked with an unsafe modifier, which requires the use of a fixed C # operator. To compile this code, you need to specify the / unsafe option when invoking the C # compiler or select the "Allow unsafe code" checkbox on the "Assembly" tab in the "Project Properties" panel in Microsoft Visual Studio. When I run this program on my machine, I get the following output:
00:00:02.0017692: Safe2DimArrayAccess 00:00:01.5197844: SafeJaggedArrayAccess 00:00:01.7343436: Unsafe2DimArrayAccess
As you can see, the safe two-dimensional array access technique is the slowest. The technique of safely handling an uneven array takes a little less time to complete than a secure two-dimensional array access technology. However, you should note that creating a jagged array takes longer than creating a multidimensional array, because creating an jagged array requires the object to be allocated on the heap for each dimension, causing the garbage collector to periodically kick. So, there is a trade-off: if you need to create many “multidimensional arrays” and you intend to access elements rarely, it’s faster to create a multidimensional array. If you need to create a "multidimensional array" only once, and you often look at its elements, a jagged array will give you better performance. Of course, in most applications the latter scenario is more common.
Roman melnyk
source share