The following test shows you how much the try / catch block cost your application performance. Therefore, please consider carefully every cases you use try / catch.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
namespace TryCatchTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Stopwatch sw = new Stopwatch();
sw.Start();
try
{
int count = 0;
for (int i = 0; i < 10000; i++)
{
count += 1;
label1.Text = count.ToString();
}
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
}
sw.Stop();
Console.WriteLine("With try / catch, the elapsed time is: " + sw.ElapsedMilliseconds + " miliseconds");
Stopwatch sw2 = new Stopwatch();
sw2.Start();
int count2 = 0;
for (int i = 0; i < 10000; i++)
{
count2 += 1;
label1.Text = count2.ToString();
}
sw2.Stop();
Console.WriteLine("Without try / catch, the elapsed time is: " + sw2.ElapsedMilliseconds + " miliseconds");
}
}
}
The output in the Console window is as follows:
With try / catch, the elapsed time is: 1364 miliseconds
Without try / catch, the elapsed time is: 1152 miliseconds
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.