Fog Creek Software
Discussion Board




Welcome! and rules

Joel on Software

Is unsafe more efficient?

It seems plausible that unsafe code (*p++, etc.)
should be more efficient than managed code.

However, I am unable to create a small C# program
that demonstrates better performance.

Can anyone exhibit such a program?

Tom Cargill
Thursday, September 19, 2002

As far as I know, this relates to code being verifiable or not, and how the framework loads its assemblies.  I am no expert on this, but my understanding so far is that code that is managed is typically verifiable, meaning that when the assembly is loaded it is checked by the load-time verifier.  This verification checks all the types used along the execution control paths adhere to the types etc - so that the garbage collector can work etc....this verification point to me seems to be were the loss of performance would occur.  Unmanaged code basically means no verification is performed.

Nick
Friday, September 20, 2002

Unsafe definitely does NOT mean unmanaged.

Anything written in C#, VB.NET etc is managed. Some c# blocks can be marked as unsafe - but they still run 100% managed.

Simon Smith
Friday, September 20, 2002

Yes you are right - further reading explains that unsafe is still managed by the CLR.

Nick
Friday, September 20, 2002

...and it all get JIT compiled to native code so why should it be any slower -- unless you tend to tweak your x86 code by hand anyway.

Dunc
Friday, September 20, 2002

There's no reason why Unsafe code should be any faster than the equivalent safe code.

However, the fact that you can do strange things with pointer arithmatic possibly means that in certain cases you could write unsafe code that would be slightly quicker than a safe code routine to do the same thing (using arrays or objects or whatever).

But is it really worth it? It may be for certain specialist routines, but for the most part, I think you're better off flying with a safety net.

James

James Shields
Friday, September 20, 2002

Thanks. Unsafe may not be what I thought.

However, Appendix A of the C#
Reference Manual says that unsafe code may be used for implementing
"a time critical algorithm."

I took this to mean that unsafe code
could achieve higher performance.
Does it mean something else?

Tom Cargill
Friday, September 20, 2002

Unsafe blocks primarily exist so that C# code can do interop with unmanaged libraries; particularly older C librarys that do a lot of pointer manipulation, pass around raw blocks of untyped bytes, that sort of thing. It could also be used for things like twiddling bytes in a memory buffer - like a DirectX surface for example.

I suspect the latter kind of use is what the writer was talking about as far as time-critical.

Chris Tavares
Friday, September 20, 2002

*  Recent Topics

*  Fog Creek Home