13

C# .Net: Fastest Way to Convert a String to an Int

C# .Net: Fastest Way to Convert a String to an Int

This will examine and benchmark many techniques to determine in C# .Net: Fastest way to convert a string to an int.

 

I ended up working on a project once where I had to read a lot of integers in from a text file. By a lot I mean over 2 million. All those numbers, read in as strings, had to be converted to integers to perform mathematical calculations. When I profiled the code in Visual Studio, I saw that the Convert.ToInt() method was taking a long time (relatively speaking) compared to other parts of the code.

 

So that’s when this curious consultant started wondering in C# .Net: what is the fastest way to convert a string to an int?

 

The Set Up:

I wrote a C# Console application to benchmark 4 different conversion techniques.

 

The code is written in Visual Studio 2012 targeting .Net Framework version 4.5 x64. The source code is available at the end of this blog so you can benchmark it on your own system if you wish.

 

In a nutshell, the code does the following:

1) Creates a specified array of strings all of which are integers.

2) It then uses 1 of 4 techniques to loop through the string array converting each string representation to the equivalent int, summing up for a total. The 4 techniques are as follows:

3)

#

Technique

Code Snippet

T0

C#’s Convert.ToInt32() method

T1

C#’s Int32.TryParse() method

T2

C#’s Int.Parse() method

T3

A custom method which loops through and converts each character in the numeric string

 

4) The sum from adding up all the values (once converted) is displayed along with the time to verify the accuracy.

5) The string array is cleared out and deleted.

 

The code assumes all numbers:

  • are positive
  • do not have thousandths separators or decimal points
  • contain no scientific or other special notations
  • and all conversions will happen with no exception testing because I’m just wanting to test the raw speed of converting.

 

I realize some geeks will look at the code and say I’m not comparing apples-to-apples since the Int.TryParse() method under the hood tests for successful conversions, but it is a method commonly used so am including it.

 

The exe file was installed and run on an Alienware M17X R3 running Windows 7 64-bit with 16 GB memory on an i7-2820QM processor.

 

The test was run for each technique over the following number of conversions:

  • 21,474,836
  • 2,147,483
  • 250,000
  • 50,000
  • 1,000

Ready! Set! Go!

Before starting, my hypothesis was that I expected it to be a virtual draw between T0 (using Convert.ToInt32() ) and T3 (converting each char to an int in the string).

 

Let’s see what happened on my machine.

 

All times are indicated in seconds.milliseconds format. Lower numbers indicate faster performance. Winner marked in green.

@ 21,474,836

@ 2,147,483

@ 250,000

@ 50,000

@ 1000

T0: Convert.ToInt32()

02.9016051

0.2808005

0.0312001

0.00

0.00

T1: Int32.TryParse()

02.8236050

0.2652005

0.0312000

0.0156000

0.00

T2: Int.Parse()

02.7612048

0.2652005

0.0312001

0.0156000

0.00

T3: Custom Method

00.1872004

0.0156001

0.00

0.00

0.00

 

Who opened up the can of whoop ass?!

It’s quite obvious the custom method T3 clearly wins completing in an order of magnitude of at least 10x faster than any of the native C# methods when doing significantly more than 50,000 conversions!!

 

Last Licks:

On my system, unless someone spots a flaw in my test code, it really makes no significant performance difference which method is used for anywhere up to a few thousand conversions. I’d use those methods for code readability.

 

If you end up working on a project like I have where you need to do a few million conversions, use the custom method for a 10x conversion performance gain. Knowing what you know now, why would you use anything else??

 

Obviously you should test on your system before micro-optimizing this functionality in your .Net application.

 

Lastly, the .Net CLR team at Microsoft needs to rewrite the native Convert.ToInt32() method to use the custom test method code in this example since the Convert.ToInt32() method seemingly performs the worst! Somebody write Microsoft! 🙂

 

The Code:

(Visited 1,071 times, 1 visits today)
  • Marty

    This test proves nothing, you are not accounting for culture-specific thousands separators (, or spaces etc.) negative numbers and E while the native methods do check. Your way is indeed fast but would unavoidably fail to parse the many fringe cases you see daily in the wild.

    • Free Coder 24

      Someone obviously didn’t read the author’s “assumptions” portion of this article.

  • Hogan Long

    To really see if your non-error checking code is faster you need to test the effect of the function call. We are talking about effects smaller than a 50,000th of a second (as we see with 50,000 we are still at 0).

    All of the tests besides T3 have a function call as overhead.

    • Fairfax

      The author quite clearly states: “The code assumes all numbers are positive and all conversions will happen with no exception testing because I’m just wanting to test the raw speed of converting. I realize some geeks will look at the code and say I’m not comparing apples-to-apples since the Int.TryParse() method under the hood tests for successful conversions, but it is a method commonly used so am including it.” Most programmers won’t write their own method for conversion and use the built in API’s, so I think it’s fair of him to include those method calls in the test and not worry about accounting for overhead.

      • Hogan Long

        And I clearly state … most of the difference between the author’s code and the other 3 tests can be accounted for by the function call.

        You can dismiss what I’m saying — or prove me wrong with a test — but don’t change what I said.

        I said nothing about negative numbers and exception handling.

        Instead I pointed out a significant difference which was NOT covered by the disclaimer you quoted.

  • Stephen van Essen

    I just stumbled on to this now, and however interesting this is, and certainly useful knowledge if you have to parse tons of non-negative numbers in strings, I have a few notes on your findings.

    First of all, the string overload of Convert.ToInt32() just calls int.Parse() with CultureInfo.CurrentCulture under the covers after a null check, so it’s a bit surprising there would be a significant difference in execution time.

    int.Parse() and int.TryParse() call respectively Number.ParseInt32() and Number.TryParseInt32(). The only difference between those 2 is that the TryParse variant returns false when parsing fails and the Parse Variant throws an exception.

    The difference in speed with your custom method is not very surprising: you’re not checking for nulls and overflows, and negative numbers don’t work: Micorsoft uses the same method in the .NET framework where those things can be ignored: for instance in the implementation of StringBuilder.AppendFormat().

  • professor

    You can speed code up even more by skipping part related to splitting up strings: with minor modification your method is capable of parsing substrings by start-end indexes directly from long string that contain entire file. With that much occurrences, it also takes considerable time.

    • David Lozinski

      Which code segment are you referring to? Example?

  • bob

    you’re not handling negative numbers

    • David Lozinski

      First sentence after point #5: “The code assumes all numbers are positive and all conversions will happen with no exception testing because I’m just wanting to test the raw speed of converting.”

  • Nethanel Rukhimovich

    Very good article!
    You assign to start inside ‘if’ but before ‘Console.WriteLine’, which is included in time calculation. More accurate way is using Stopwatch timer, and starting in *immediately* before the stuff you’re want to measure.

    • David Lozinski

      Hi there:

      Fair point on the start time assignment. I’ll update the code.

      As for using the stopwatch, I’ll leave that as an exercise to you to show how much more accurate it is or isn’t. 😉

  • Pramod Nair

    Informative blog!