c# - How Do I Prevent JIT Compiler From Optimising Out This Method -


i have extension method looks following:

//[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 method when parsing file binaryreader skip block of whitespace characters, amongst other things. have found jit compiler optimising out, when call so:

// skip white space this.reader.takewhile(iswhitespace);//.firstordefault(); 

i have tried adding [methodimpl(...)] attribute instruct jit compiler not optimise out method, not work. write implementation of manipulates underlying stream buffer position out of curiosity know why so.

the ways have found prevent optimisation use ienumerable results (eg - via call .firstordefault() commented above) or copy code calling method. have tried preventing optimisation of calling methods, using methodimplattribute, not work. strangely, optimisation turned off under debug build shouldn't occuring in situation. know way prevent optimisation?

no, jit isn't optimizing out. however, none of code executed - because you're ignoring returned value. until first call movenext(), none of code in iterator block run. has nothing jit, , how iterator blocks work.

you may want read articles on iterator blocks (basics, implementation details) , eric lippert's "psychic debugging" blog post (part 1; part 2).

note calling firstordefault() read first character. sounds want consume whole stream until condition fails - means using count() iterate on entire returned sequence.

alternatively - , preferrably imo - write "active" method void return type this. if you're not interested in return value of method, that's signal it's not ideal method call. (that's not always case, is.)


Comments

Popular posts from this blog

linux - Mailx and Gmail nss config dir -

c# - Is it possible to remove an existing registration from Autofac container builder? -

php - Mysql PK and FK char(36) vs int(10) -