0

C# ConvertTo Vs Parse

C# ConvertTo Vs Parse

This article details the benchmark and performance showdown: C# ConvertTo vs Parse methods.

In any programming language, data type conversions are inevitably going to happen. C# programmers have quite a few tools up their sleeves thanks to the .Net framework.

 

A few popular methods for each data type include:

  • ConvertTo
  • Parse
  • TryParse
  • Try-Catch exception handling

and so on.

 

What isn’t often considered are the performance implications.

 

For the purposes of this article, we’ll be examining the performance implications of the first two with:

TryParse and the Try-Catch construct have already been examined in detail.

 

Ready? Let’s Go!

 

Getting Started

3 string arrays are initialized with 20 string representations of int, bool, and DateTime values. These will be the fixed values we’ll be converting for every run.

The code then performs the conversions using the associated Parse() and ConvertTo() methods.

The C# is written in Visual Studio 2015 targeting .Net Framework version 4.7.1 x64. The source code is available at the end of this blog so you can benchmark it on your own system.

 

Who won?

Let’s see what happened on my machine.

All times are indicated in seconds.milliseconds format.

Lower numbers indicate faster performance.

 

1,000

10,000

100,000

1,000,000

10,000,000

int.Parse()

00.0000892

00.0008375

00.0086945

00.0727122

00.8015826

Convert.ToInt32()

00.0005854

00.0010939

00.0075113

00.0777216

00.7841260

 

bool.Parse()

00.0000237

00.0001189

00.0011681

00.0116875

00.1037218

Convert.ToBoolean()

00.0000150

00.0001580

00.0010781

00.0115476

00.1136900

 

DateTime.Parse()

00.0031217

00.0099275

00.1080647

01.0871715

11.0092108

Convert.ToDateTime()

00.0015126

00.0102976

00.0994469

01.0265536

10.5169374

 

The winner is –

– nobody. That’s right.

Nobody.

Unless someone spots a flaw in my code, there’s really no clear cut winner when it comes to speed.

The times flipped back and forth after several runs with no discernible pattern.

What can I say? We’re calling this one a draw.

So should you use the ConvertTo or Parse methods?

Well, assuming you’re not concerned about exceptions or null values, y’know that old saying… ta-may-toe or tah-mah-toe.

 

The Code:

 

David Lozinski