Using System;
Using System. Text;
Performance Loss of namespace Exception Handling
{
/// <Summary>
/// C # exception handling performance loss
/// Author: jehnjehn
// Email: jehn@foxmail.com
/// [Principle recommended by jehnjehn: avoid exceptions as much as possible rather than capture and handle exceptions]
/// </Summary>
Class Program
{
Static void Main (string [] args)
{
Int testTimes = 10000; // Number of custom tests.
StringBuilder sb = new StringBuilder (string. Concat ("executed", testTimes,
"Performance comparison of several exception handling methods during the next cyclic operation (the shorter the running time, the higher the performance )"));
Sb. AppendLine (Environment. NewLine );
System. Diagnostics. Stopwatch w = new System. Diagnostics. Stopwatch ();
// Method 1: avoid exceptions instead of capturing exceptions
Int a = 0;
W. Start ();
For (int I = 0; I <= testTimes; I ++)
{
Int32.TryParse ("a", out );
}
W. Stop ();
Sb. AppendLine (string. Concat ("TypParse avoid exceptions:", w. ElapsedMilliseconds, "ms "));
// Shield all exceptions. This method is only used for testing.
W. Reset ();
W. Start ();
For (int I = 0; I <= testTimes; I ++)
{
Try
{
Int32.Parse (null );
}
Catch {}
}
W. Stop ();
Sb. AppendLine (string. Concat ("shielded catch all exceptions:", w. ElapsedMilliseconds, "ms "));
// Throw the specified exception instance
W. Reset ();
W. Start ();
For (int I = 0; I <= testTimes; I ++)
{
Try
{
If (! Int32.TryParse ("a", out ))
{
Throw new ArgumentNullException (I. ToString ());
}
}
Catch {}
}
W. Stop ();
Sb. AppendLine (string. Concat ("throw the specified exception instance:", w. ElapsedMilliseconds, "ms "));
// Static exception variable, test only
Int B = 0;
Exception ex = new Exception ();
W. Reset ();
W. Start ();
For (int I = 0; I <= testTimes; I ++)
{
Try
{
If (! Int32.TryParse ("a", out B ))
{
Throw ex;
}
}
Catch {}
}
W. Stop ();
Sb. AppendLine (string. Concat ("throwing a static exception:", w. ElapsedMilliseconds, "ms \ n "));
Console. WriteLine (sb );
System. IO. File. WriteAllText ("result.txt", sb. ToString ());
Console. WriteLine ("Press any key to continue ...");
System. Diagnostics. Process. Start ("result.txt ");
// Console. ReadKey (true );
}
}
}
The result is as follows:
During the execution of 10000 cyclic operations, several exception handling methods (the shorter the running time, the higher the performance) TypParse avoid exceptions: 1 ms shielded capture all exceptions: 836ms throw the specified exception instance: static exception thrown in 185 ms: ms
This is an excerpt from the event where you want to complain about Dongfeng ~