I was reviewing some code given to us by a third-party outsourcing firm and ran across this little gem:
try
{
int i = strOriginalData.IndexOf("\r\n");
////System.Diagnostics..EventLog.WriteEntry("i", i.ToString());
}
catch (System.Exception ex)
{
////System.Diagnostics..EventLog.WriteEntry("ex", ex.Message);
}
My question is will the compiler completely optimize this out? When I look at the compiled assembly in Reflector, it shows this:
try
{
i = this.strOriginalData.IndexOf("\r\n");
}
catch (Exception exception1)
{
ex = exception1;
}
The declaration for i has been moved to the top of the method, and additional declaration of type Exception is at the top of the method also.
So, since this code doesn’t really do anything, I was wondering if the compiler is smart enough to see that this code does nothing and can optimize it out.
So, as you’ve found via Reflector, the C# compiler will not optimize it out. Whether the JIT compiler will is another question. But, I would guess the answer is almost certainly not.
Why? Because the JIT compiler doesn’t know that
IndexOfis a boring method. In other words, as far as the JIT compiler knows,string.IndexOfcould be defined asObviously, in that case optimizing out that line would be bad.