I have an extension method that looks like this:
//[MethodImpl(MethodImplOptions.NoOptimization)] public static IEnumerable<char> TakeWhile(this BinaryReader reader, Func<int, bool> condition) { while (condition(reader.PeekChar())) { char c = reader.ReadChar(); yield return c; } }
I use this method when parsing a file with BinaryReader to skip the space character block, among other things. I found that the JIT compiler optimizes it when I call it like this:
// Skip white space this.reader.TakeWhile(IsWhiteSpace);//.FirstOrDefault();
I tried adding the [MethodImpl (...)] attribute to instruct the JIT compiler not to optimize the method, but it does not work. Now, obviously, I could write another implementation of this that manipulates the base position of the stream buffer, but out of curiosity I would like to know why this is so.
The only ways I found to prevent optimization are to use IEnumerable results (for example, by calling the .FirstOrDefault () method as above) or copying the code to the calling method. I tried to prevent the optimization of the calling methods using MethodImplAttribute, but this will not work. Oddly enough, optimization is completely disabled under the Debug assembly, so it should not occur in any situation. Does anyone know another way to prevent optimization?
source share