views:

111

answers:

2

I am working on a math library for my DirectX 3D engine in C#. I am using SlimDX, which is a wonderfuly put together and powerful library. SlimDX provides quite a few math classes, but they are actually wrappers around native D3DX objects, so while the objects themselves are very, very fast, the interop is not I presume, because my managed C# code outperforms them.

My specific question has to do with floating-point comparison. The sort-of canonical way is to define an epsilon value, and compare the value to the difference between the floating-point values to determine closeness, like so:

float Epsilon = 1.0e-6f;
bool FloatEq(float a, float b)
{
  return Math.Abs(a - b) < Epsilon
}

The function call overhead would swamp the actual comparison, so this trivial function would be inlined in C++, will the C# compiler do this? Is there a way to tell the C# compiler that I want a method inlined?

+7  A: 

The C# compiler doesn't perform inlining - but the JIT may well do so in this case. That's certainly the piece which would perform inlining, if anything.

EDIT: I would expect it to inline in this case, but it's hard to tell without loading the code into something like cordbg with JIT optimizations turned on. Each different CLR version may well have different tweaks to its inlining (including the 64 bit vs 32 bit CLRs) so I'm reluctant to say anything too definite.

Jon Skeet
The JIT can be fairly intelligent about inlining, when run outside the debugger. It can inline the `Math.Abs` method itself, for instance.
Tim Robinson
Now the question is: WILL IT in this case (assuming optimised code and no debugger)?
Mau
@Mau: Editing...
Jon Skeet
Thanks for the explanation, it actually makes sense when I read some of the documents from Microsoft concerning performance with the .NET system.The basic rule of thumb being that trying to beat the CLR in performance is often, but not always, a waste of effort. :-)
Chris D.
+1  A: 

Here's some info about the circumstances under which the JIT won't perform inlining;

http://blogs.msdn.com/b/davidnotario/archive/2004/11/01/250398.aspx

C.McAtackney
Thanks for the link, that actually explains a lot.
Chris D.