Gamefest 2007: The Costs of Managed Code: The Avoidable and the Unavoidable

A few weeks ago I spoke at Gamefest 2007 where I delivered this talk:

The Costs of Managed Code: The Avoidable and the Unavoidable

This talk is for those who want to understand the inescapable performance consequences of the managed programming method: the things you cannot avoid and the things you can. The presentation explains those few characteristics of managed code, such as array bounds checking, application domain isolation, and write barriers, that profoundly affect the code generation at a primitive level. Comparing and contrasting the consequences for the .NET Compact Framework and the classic .NET runtime, the talk explains the reasons for these overheads, the benefits they provide, and what practices minimize the associated costs. Additionally, we discuss some commonly occurring costs, such as boxing, that aren’t inherent to all managed code, and we offer some tips for minimizing those costs. Speaker: Rico Mariani

The talk was based on an older article that I wrote on Qualitative Code Differences in Managed Code which was itself based on an internal paper written by my colleague Vance Morrison (thank you again Vance).

You can see the talk at the XNA Content Creators Site and I encourage you to look at the other talks too as this whole series was very popular and many of the concepts are broadly useful.

Comments (3)

  1. Norman Diamond says:

    Not gaming, but here is one way that I had to find recently in order to avoid a cost of managed code.

    Graphics.DrawImage was performing unacceptably slowly.  ::StretchBlt runs around 50 times as fast.  Graphics.GetHdc gets a write-only HDC, so passing it to ::StretchBlt got us a black picture box at a very acceptable rate of speed.  Other managed methods like GetHbitmap got us out-of-memory errors.

    Solution:  Don’t read the source image in managed code at all.  Write a C++ DLL to read the image and return an HDC.  Then the C# program can call StretchBlt and our picture box performs correctly at a very acceptable rate of speed.

    I’m just estimating the speed difference at a factor of 50.  It might be 40.  It might be 100.  The image file was a 24bpp Jpeg and the picture box was on a 32bpp screen.  This was under 32-bit XP.  I think I’m going to recommend 64-bit XP for the production product, but we’re going to stick with the native DLL and P/Invoke as described above.

  2. conseq says:

    Norman Diamond:

    GDI+ = slow.

    .NET graphics on top of GDI+ = slow^2.

    It’s nearly almost faster (by an order of magnitude) to p/invoke into plain old GDI when doing any amount of user-drawing onto a WinForm.