Chris Dunaway
Chris Dunaway

Reputation: 11216

c#: Will this code get optimized out?

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.

Upvotes: 1

Views: 461

Answers (3)

Henk Holterman
Henk Holterman

Reputation: 273169

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.

Upvotes: 2

Domenic
Domenic

Reputation: 112807

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.

Upvotes: 13

Jon Skeet
Jon Skeet

Reputation: 1499770

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

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

Upvotes: 6

Related Questions