Does Try-catch affect program performance?

Source: Internet
Author: User
Tags finally block mscorlib
Does Try-catch really affect program performance?
Today and TL debate try-catch use of the problem, whether for the code to look beautiful and put all the code under the Try-catch, I take it for granted, but not in-depth research on the implementation mechanism of try-catch, can not say convincing reasons, Find A. NET Try-catch analysis on the internet today and share with you
Many posts have analyzed the mechanisms of try-catch and their impact on performance.
However, there is no evidence that Try-catch is too lossy for system performance, especially in managed environments. Remember that there is a netizen in the garden. Using stopwatch to analyze try-catch in different situations, compared with the code without Try-catch, the time index of code running, the result is not very big difference.
Now let me combine il to analyze try-catch.
Mechanism analysis
The basic exception capture and processing mechanism in. Net is done by the try...catch...finally block, which has completed the monitoring, capturing and processing of the anomaly respectively. A try block can correspond to 0 or more catch blocks, which can correspond to 0 or a finally block. However, a try without catch does not seem to make sense, and if the try corresponds to more than one catch, then after the exception is detected, the CLR will search the code of the catch block from top to bottom and filter the corresponding exception through the exception filter, and if not found, the CLR will follow the call stack, A matching exception to a higher-level search, if the corresponding exception is still not found at the top of the stack, an unhandled exception is thrown, and the code in the catch block is not executed. So the catch block closest to the try will be traversed first.
If you have the following code:
Try
{
Convert.ToInt32 ("Try");
}
catch (FormatException Ex1)
{
String catchformatexception = "Catchformatexception";
}
catch (NullReferenceException ex2)
{
String catchnullreferenceexception = "Catchnullreferenceexception";
}
Finally
{
string finally = "Finally";
}
The corresponding IL is as follows:
. method private Hidebysig instance void Form1_Load (object sender,
class [Mscorlib]system.eventargs E] CIL managed
{
Code size (0x35)
. maxstack 1
. Locals init ([0] class [Mscorlib]system.formatexception Ex1,
[1] string catchformatexception,
[2] class [Mscorlib]system.nullreferenceexception ex2,
[3] String catchnullreferenceexception,
[4] string Finally)
Il_0000:nop
Il_0001:nop
Il_0002:ldstr "Try"
Il_0007:call int32 [Mscorlib]system.convert::toint32 (String)
Il_000c:pop
Il_000d:nop
IL_000E:LEAVE.S il_0026
il_0010:stloc.0
Il_0011:nop
Il_0012:ldstr "Catchformatexception"
Il_0017:stloc.1
Il_0018:nop
IL_0019:LEAVE.S il_0026
Il_001b:stloc.2
Il_001c:nop
Il_001d:ldstr "Catchnullreferenceexception"
Il_0022:stloc.3
Il_0023:nop
IL_0024:LEAVE.S il_0026
Il_0026:nop
IL_0027:LEAVE.S il_0033
Il_0029:nop
Il_002a:ldstr "Finally"
Il_002f:stloc.s Finally
Il_0031:nop
Il_0032:endfinally
Il_0033:nop
Il_0034:ret
il_0035:
Exception Count 3
. Try il_0001 to il_0010 catch [mscorlib]system.formatexception handler il_0010 to il_001b
. Try il_0001 to il_0010 catch [mscorlib]system.nullreferenceexception handler il_001b to il_0026
. Try il_0001 to il_0029 finally handler il_0029 to il_0033
}//End of method Form1::form1_load
The lines at the end reveal how the IL handles exception handling. Each item in the last three lines is called exception handing CLAUSE,EHC composition exception handing Table,eht is separated from the normal code by a ret return instruction.
As can be seen, FormatException ranked first in the EHT.
When the code executes successfully or vice versa, the CLR traverses eht:
1. If an exception is thrown, the CLR will find the corresponding EHC (il_0001 to il_0010 as the scope of the detection code) based on the "address" of the code that throws the exception, in this case the CLR will find 2 EHC, the FormatException will be first traversed, and the appropriate EHC.
2. If the returned code address is within il_0001 to il_0029, then the code in the finally handler that is il_0029 to il_0033 is also executed, regardless of whether the code was executed successfully or not.
In fact, the catch and finally traversal work is done separately, as mentioned above, the first thing the CLR does is traverse the catch, when the appropriate catch block is found, and then traverse the corresponding finally, and the process will be recursive at least two times, because the compiler will C # 's try ... Catch...finally translates into two levels of nesting in IL.
Of course, if the corresponding catch block is not found, then the CLR executes the finally and immediately interrupts all threads. The code in the finally block is sure to be executed, regardless of whether the try detects an exception.
Recommendations for improvement
The above content can be drawn:
If you use "Try-catch" and catch an exception, the CLR does nothing but traverse the Catch entry in the exception handing table, and then iterate through the finally item in the exception handing table again, The elapsed time is almost always spent traversing the exception handing table, and if the exception is not caught, the CLR simply traverses the finally item in the exception handing table with minimal time required.
and "Try-catch" after the traversal of the execution of the corresponding operation time, according to your specific code, "Try-catch" caused by only monitoring and triggering, should not be this part of the code time is also counted "try-catch" consumption.
Therefore, you can consider both performance and code review, the following guidelines are generally recommended:
1. Try to give the CLR a clear exception message, do not use exception to filter the exception
2. Try not to write Try...catch in the loop
3. Try as few code as possible, use multiple catch blocks if necessary, and write the type of exception that is most likely to be thrown, at the nearest location from the try
4. Don't just declare a exception object, not handle it. This increases the length of the exception handing table in vain.
5. Use the performance counter utility's "CLR Exceptions" to detect anomalies and properly optimize
6. Using the member's Try-parse mode, if an exception is thrown, replace it with false
conclusion, although the Try-catch will consume a little time, but the program personnel can not Tanhusebian, through the above analysis, not to say "Try-catch" will wear out or affect performance, rather say "Try-catch" and other code, just the performance of the average consumer, But for the code writing review considerations, try to take care of "try-catch" it.
  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.