Вопрос

In c#, how much time is expended in an empty try catch block?

I've heard that it is between 10-55ms, but i'm leaning to zero/one as the compiler will replace the empty try catch with a no-op placeholder.

any compiler experts that can verify this information?

Это было полезно?

Решение

If when you say "empty try catch block", you mean literally:

try
{
}
catch
{
}

Then yes, when building with compiler optimizations turned on (that is, "release" mode), it will not emit any IL instructions. For example:

private void Test()
{
    try
    {
    }
    catch
    {
    }
}

Compiles to:

IL_0000:  ret

Which is the same as if it were an empty method.

However, when optimizations are turned off (that is, "debug" mode), it emits:

IL_0000:  nop         
IL_0001:  nop         
IL_0002:  nop         
IL_0003:  leave.s     IL_000A
IL_0005:  pop         
IL_0006:  nop         
IL_0007:  nop         
IL_0008:  leave.s     IL_000A
IL_000A:  nop         
IL_000B:  ret 

Whereas an empty method would be:

IL_0000:  nop         
IL_0001:  ret 

Whether or not these IL instructions are stripped when the JIT compiler is executed, I am not positive. But this would still only apply when compiling without compiler optimizations as with them turned on the try/catch is stripped out during the initial compile to IL before it hits the JIT compiler.

EDIT: I just realized I may not have actually answered the question:

In release mode, zero time is expended on an empty try/catch.
In debug mode, a non-zero time is expended on an empty try/catch as it still emits the necessary IL code for debugging/breakpoint purposes and requires some JIT compilation. However, it would be a negligibly small amount of time. Definitely nowhere near the neighbourhood of "10-55 milliseconds".

Другие советы

If you check compiled code by proper software (like ILspy or Reflector), you can see that empty block will be deleted completley by compiler.

ILSpy image

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top