Gamefest 2007: 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

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.