Disable compiler optimisation for a specific function or block of code (C#)

You can decorate a specific method (or a property getter/setter) with [MethodImpl(MethodImplOptions.NoOptimization)] and [MethodImpl(MethodImplOptions.NoInlining)], this will prevent the JITter from optimizing and inlining the method:

[MethodImpl(MethodImplOptions.NoOptimization | MethodImplOptions.NoInlining)]
private void MethodWhichShouldNotBeOptimized()
{ }

However, there isn’t a way to apply this attribute to a block of code. Also NoOptimization attribute was added in .NET 3.5, which might be important for legacy code or Compact Framework.

Leave a Comment

tech