It’s been almost a month since I first thought about using unsafe C# code. The application is still being developed, but the parts using the unsafe code are pretty much finished. Overall, I’m very happy with the results. Performance is more than acceptable and it’s spending less than 1% of the running time in the GC.

Here are a few of the guidelines I tried to follow and are probably common sense for using unsafe code in C#:

  • Limit the number of methods that use unsafe types.
  • The less methods that need to be decorated with the unsafe keyword, the better.
  • Limit the lifetime of unsafe types.
  • In my application, I only need the blocks of memory for a single parsing, then I release it.
  • Use the correct memory allocation functions.
  • HeapAlloc, HeapFree, and GetProcessHeap are the MSDN recommended methods to use.

I’m sure others could add to this list. The first two helped keep me focused on separating out my classes in keeping with SOLID Principles (as so far as I understand them). Of course that’s probably a whole post itself.