It's only try/finally blocks with empty finally blocks that get optimized
to no try/finally at all. e.g.
int i = 1;
try
{
i = 2;
i = 3;
}
finally
{
Debug.WriteLine(i);
}
Console.WriteLine(i);
With DEBUG defined, the above code won't be optimized. With DEBUG not
defined, the C# compiler will emit IL equivalent to:
int num = 1;
num = 2;
num = 3;
Console.WriteLine(num);
... of course the JIT will optimize that to just Console.WriteLine(3);
Empty catch blocks never cause the C# compiler to optimize away the try
With DEBUG undefined, the following code:
int i = 1;
try
{
i = 2;
i = 3;
}
catch(Exception)
{
Debug.WriteLine(i);
}
...will emit IL equivalent to:
int num = 1;
try
{
num = 2;
num = 3;
}
catch (Exception)
{
}
And--as with DEBUG defined in the try/finally example--the JIT will not
optimize any of it.
-- Peter
On Tue, 7 Aug 2007 09:37:45 -0700, Greg Young <[EMAIL PROTECTED]>
wrote:
>OFF TOPIC:
>Its also interesting because a try {} catch {} is optimized out with
>an empty catch (finally with empty finally) ... this changes the JIT
>compiled code. These changes can have visible side effects ...
>
>as such code like
>
>try {
>}
>catch(Exception Ex) {
> Debug.Write(Ex);
>}
>
>can have slightly differing behaviors if #DEBUG is enabled.
>
>Personally this is one optimization I could do without :)
>
>Cheers,
>
>Greg
>
>On 8/7/07, Marc Brooks <[EMAIL PROTECTED]> wrote:
>> > Usually when people talk about compiler optimizations they mean the
JIT.
>> > CSC does precious little optimization.
>>
>> Isn't that the truth (of course that feeds my need for speed at compile
time)
>>
>> >
(http://msdn.microsoft.com/msdnmag/issues/05/01/COptimizations/default.aspx
>> > ?side=true#a)
>>
>> VERY interesting reminder tucked in that document, thanks!
>>
>> "A Try-Finally with no code in the Try is left completely alone. This
>> is because the semantics of code executing in a Finally block and
>> outside of it are different. Asynchronous ThreadAbort exceptions
>> (those thrown by another thread) may interrupt the execution of all
>> code, except for code found in Finally blocks."
===================================
This list is hosted by DevelopMentorĀ® http://www.develop.com
View archives and manage your subscription(s) at http://discuss.develop.com