开发者

c#: Will this code get optimized out?

开发者 https://www.devze.com 2023-01-28 18:41 出处:网络
I was reviewing some code given to us by a third-party outsourcing firm and ran across this little gem:

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 = thi开发者_Go百科s.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 IndexOf is a boring method. In other words, as far as the JIT compiler knows, string.IndexOf could be defined as

public int IndexOf()
{
   CallAWebService();
}

Obviously, in that case optimizing out that line would be bad.


How would the compiler know that IndexOf had no side-effects?

So basically no, it's not going to optimize it out.


No, it won't be optimized out.

On the other hand, it is a very small overhead. Compared to the cost of string.IndexOf() setting up the catch block is negligible.

There would be a cost if there ever was an exception, but that's not likely.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号