In order to do so you need to compile your code using the /unsafe switch. This is required because unsafe code cannot be verified by the CLR.
In Visual Studio you can enable this in the Properties panel.
In this post I would like to run a simple experiment to measure the difference in performance when you run a very simple matrix filter: computes the square of each number in the matrix.
The safe method:
Inside an unsafe block it is possible to use pointers in C#. Surprised?
This is the code that compares the performance of the two versions:
The output is the following:
Safe time: 0.4410526
Unsafe time: 0.1252171
Unsafe is 3.52230326369162 times faster
There is a lot to say about unsafe in C# but I don't want to go deep in the subject because the use of pointers is almost never required and it should be avoided if possible.
The important lessons from this post are:
- C# allows to use pointers and manage the memory directly if you need it
- Unsafe code in C# can improve performance
- Always measure performances to justify the use of unsafe code