Sunday, 3 February 2013

Unsafe and Fixed keywords in C#

C# allows you to manage memory directly when needed mainly for performance reasons.

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:
The unsafe method:
The unsafe keyword denote that the method contains unsafe code. The keyword fixed is required to pin a managed object (matrix in this case) in order to avoid that the garbage collector move the object while we perform the operation.

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



2 comments:

What you think about this post? I really appreciate your constructive feedback (positive and negative) and I am looking forward to start a discussion with you on this topic.