English
Français

Blog of Denis VOITURON

for a better .NET world

C# TryParse Vs Try Catch

Posted on 2022-09-02

This article analyses the C# performance between the use of TryParse and Try Catch. It often happens that we receive data, whose format is suspect, and that we have to convert it to a specific data type.

For this, the developer frequently uses TryParse or Try Catch. But what is the best solution?

Each has its advantages and disadvantages depending on the context. I think most developers would suggest:

Personally, I recommend to use TryParse in all cases and to trace the erroneous data when the result of this method comes back with the value False.

More precisely, by performing a Benchmark of the following conversions, we can see that TryParse is always faster. The conversion can be several hundred times slower, when a lot of data are erroneous and trigger exceptions.

using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;

var summary = BenchmarkRunner.Run(typeof(Program).Assembly);

public class TryCatchOrTryParse
{
    private static Random random = new Random();

    private string _myDate = "";
    private string _myNumber = "";

    public TryCatchOrTryParse()
    {
        PercentageWrongValues = 80; // 5 or 80

        if (random.Next(0, 100) > PercentageWrongValues)
        {
            _myNumber = RandomString("1234567890", 6);
            _myDate = $"{random.Next(1000, 9999)}-01-12";
        }
        else
        {
            _myNumber = RandomString("ABCDEFGHI", 6);
            _myDate = $"{random.Next(1000, 9999)}-01-32";
        }

        string RandomString(string chars, int length)
        {
            return new string(Enumerable.Repeat(chars, length)
                .Select(s => s[random.Next(s.Length)]).ToArray());
        }
    }

    public int PercentageWrongValues { get; set; }

    [Benchmark]
    public int? Int32_TryParse()
    {
        bool ok = Int32.TryParse(_myNumber, out Int32 result);
        return ok ? result : null;
    }

    [Benchmark]
    public int? Int32_TryCatch()
    {
        try
        {
            return Convert.ToInt32(_myNumber);
        }
        catch
        {
            return null;
        }
    }

    [Benchmark]
    public DateTime? DateTime_TryParse()
    {
        bool ok = DateTime.TryParse(_myDate, out DateTime result);
        return ok ? result : null;
    }

    [Benchmark]
    public DateTime? DateTime_TryCatch()
    {
        try
        {
            return Convert.ToDateTime(_myDate);
        }
        catch
        {
            return null;
        }
    }
}

The following table shows the average execution time of these methods, thanks to the benchmark library BenchmarkDotNet.

The first average is based on the assumption that 5% of the converted data are wrong. The second average assumes that 80% of the converted data are erroneous.

BenchmarkDotNet=v0.13.2, OS=Windows 11 (10.0.22000.856/21H2)
Intel Core i7-1065G7 CPU 1.30GHz, 1 CPU, 8 logical and 4 physical cores
.NET SDK=6.0.400
  [Host]     : .NET 6.0.8 (6.0.822.36306), X64 RyuJIT AVX2
  DefaultJob : .NET 6.0.8 (6.0.822.36306), X64 RyuJIT AVX2

| % Wrong | Method           |  TryParse   |  Try Catch  |
|---------|------------------|-------------|-------------|
|    5%   | Int32            |    16.34 ns |    17.41 ns | => x   1.06
|    5%   | Date             |   209.44 ns |   219.68 ns | => x   1.04
|---------|------------------|-------------|-------------|
|   80%   | Int32            |    19.02 ns |  9289.64 ns | => x 488.41
|   80%   | Date             |   195.15 ns |  8304.45 ns | => x  45.55
|---------|------------------|-------------|-------------|

Languages

EnglishEnglish
FrenchFrançais

Follow me

Recent posts