Will try-catch affect program performance?
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.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.
