Does Try-Catch really affect program performance?
Today I was arguing with TL about the use of try-catch, whether to put all the code from this method into try-catch for the sake of the beautiful appearance of the code. I took it for granted. I hold an objection, but I have not studied the implementation mechanism of try-catch in depth, and I cannot give a convincing reason. Today I found a .net try-catch analysis on the Internet, and I would like to share it with you
Many posts have analyzed Try -Catch mechanism and its impact on performance.
But there is no evidence that Try-Catch consumes too much system performance, especially in a hosting environment. I remember that a netizen in the garden used StopWatch to analyze the code running time indicators of Try-Catch under different circumstances compared with the code without Try-Catch, and the results were not very different.
Next, let me analyze Try-Catch based on IL.
● Mechanism Analysis
The basic exception capturing and processing mechanism in .Net is completed by the try...catch...finally block, which completes the monitoring, capturing and processing of exceptions respectively. A try block can correspond to zero or more catch blocks, and can correspond to zero or one finally block. However, a try without a catch seems meaningless. If the try corresponds to multiple catches, then after detecting an exception, the CLR will search the code of the catch block from top to bottom and filter the corresponding exception through the exception filter. If it is not found, Then the CLR will search for matching exceptions along the call stack to higher levels. If the corresponding exception is still not found at the top of the stack, an unhandled exception will be thrown. At this time, the code in the catch block will not be executed. . So the catch block closest to try will be traversed first.
If there is 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 53 (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_00 10 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 last few lines of code reveal How IL handles exception handling. Each Item in the last three lines is called Exception Handing Clause, EHC forms the Exception Handing Table, and EHT is separated from normal code by the ret return instruction.
It can be seen that FormatException is ranked first in EHT.
When the code executes successfully or returns vice versa, the CLR will traverse the EHT:
1. If an exception is thrown, the CLR will find the corresponding EHC based on the "address" of the code that throws the exception (IL_0001 to IL_0010 is the range of the detection code). In this example, the CLR will find 2 EHCs, and FormatException will be traversed first. to, and is a suitable EHC.
2. If the returned code address is within IL_0001 to IL_0029, the finally handler, that is, the code in IL_0029 to IL_0033 will also be executed, regardless of whether it is returned due to successful execution of the code.
In fact, the traversal work of catch and finally is carried out separately. As mentioned above, the first thing the CLR does is to traverse the catch. When the appropriate catch block is found, it then traverses the corresponding finally; and this process will be performed recursively at least Twice, because the compiler translates C#'s try...catch...finally into two levels of nesting in IL.
Of course, if the corresponding catch block is not found, the CLR will directly execute finally and then immediately interrupt all threads. The code in the Finally block will definitely be executed regardless of whether try detects an exception.
● Improvement suggestions
It can be concluded from the above:
If "Try-Catch" is used and an exception is caught, all the CLR does is to traverse the Catch items in the Exception Handing Table; and then traverse the Exception Handing Table again Finally items, almost all the time is spent traversing the Exception Handing Table; and if no exception is caught, the CLR only traverses the Finally items in the Exception Handing Table, and the time required is minimal.
The time it takes to execute the corresponding operation after "Try-Catch" traversal is determined according to your specific code. "Try-Catch" only causes monitoring and triggering, and this part of the code time should not be counted as "Try-Catch" "Consumption.
Therefore, we can consider both performance and code review. It is generally recommended to have the following guidelines:
1. Try to give the CLR a clear exception information, and do not use Exception to filter exceptions
2. Try not to write try...catch in In the loop
3. Try as little code as possible, use multiple catch blocks if necessary, and write the exception type that is most likely to be thrown in the position closest to try
4. Don’t just declare one Exception object, but Don't deal with it. Doing so increases the length of the Exception Handing Table in vain.
5. Use the "CLR Exceptions" of the performance counter utility to detect exceptions and optimize appropriately
6. Use the member's Try-Parse mode. If an exception is thrown, replace it with false
Conclusion, although Try-Catch will consume It takes a while, but there is no need for programmers to talk about it. Through the above analysis, rather than saying that "Try-Catch" will consume or affect performance, it is better to say that "Try-Catch" is just an ordinary consumer of performance like other codes, but it does not Regarding code writing review considerations, it is better to pay attention to "Try-Catch" as much as possible.