35

Possible Duplicate:
Inline functions in C#?

In c++ we can force function inlining.

Is this also possible in c#? sometimes, and when the method is small, it gets inlined automatically. But is it possible force inlining functions in c#/.Net?

7
  • As mentioned, duplicate. Also, don't. The JIT compiler is really good at this and has a really good algorithm. You'll get better performance by leaving it alone. Commented Sep 6, 2012 at 15:59
  • 3
    @marr75 (As of .net 4.0) The inlining algorithm is pretty dumb. It quite often makes bad decisions. Being able to manually override them would be quite nice. Commented Sep 6, 2012 at 16:02
  • @CodesInChaos Agree to disagree, has always worked well for me. Corner cases more often require datastructure changes than microoptimizations in most of my uses. Commented Sep 6, 2012 at 16:06
  • 4
    @Eregrith Ironically googling "C# request inline" now brings this as the top answer Commented Aug 24, 2015 at 16:10
  • 3
    Here's a use-case for you: if you inline code that checks a license or something like that then any hacker now has a lot more code to chop out than simply the one method everything calls. Commented May 3, 2017 at 23:29

1 Answer 1

84

Sort of. It's not under your direct control to turn on for sure. It's never inlined in the IL - it's only done by the JIT.

You can explicitly force a method to not be inlined using MethodImplAttribute

[MethodImpl(MethodImplOptions.NoInlining)]
public void Foo() { ... }

You can also sort of "request" inlining as of .NET 4.5:

[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Foo() { ... }

... but you can't force it. (Prior to .NET 4.5, that enum value didn't exist. See the .NET 4 documentation, for example.)

Sign up to request clarification or add additional context in comments.

4 Comments

Nice, didn't know about the new enum value. That could be useful in some of my high performance code.
Why does it not offer forced inlining and only offers suggestive / requests?
@WDUK because it cannot offer to force inlining. In no language I know can inlining be forced; e.g. how do you think should a recursive function be inlined? Therefore, in C#, C++ etc. the most the programmer can do is to give a hint to the compiler that this method should probably inlined, if possible.
@ThomasFlinkow i would have thought if you request a forceful inline, it will either simply fail to compile or produce the wrong desired result, and that would be on the developer to decide when to and when not to force it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.