Inline expansion in C#
Asked Answered
O

2

8

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?

Overburden answered 13/7, 2010 at 11:13 Comment(0)
S
7

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.

Seppala answered 13/7, 2010 at 11:14 Comment(3)
The JIT can be fairly intelligent about inlining, when run outside the debugger. It can inline the Math.Abs method itself, for instance.Orford
Now the question is: WILL IT in this case (assuming optimised code and no debugger)?Potherb
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. :-)Overburden
S
1

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

Link

Spirit answered 13/7, 2010 at 11:22 Comment(1)
Thanks for the link, that actually explains a lot.Overburden

© 2022 - 2024 — McMap. All rights reserved.