Click here to Skip to main content
Click here to Skip to main content
Technical Blog

Tagged as

String to Integer conversion Internals

, 5 Nov 2011 LGPL3
Rate this:
Please Sign up or sign in to vote.
String to Integer conversion Internals

Dear reader,

Today, I was thinking about ways to convert strings to integer (32 bit) in C#. Yes of course you might think it's pretty well-known to every one right? Of course, I agree. But most developers I see around do not know the hidden facts about these things and also do not know how to use them effectively.

Let me list out 3 of them here:

  1. Convert.ToInt32
  2. Int32.Parse
  3. Int32.TryParse

But I started to ask myself a few questions:

  • When to choose each of those?
  • Why are there three ways?
  • Are there any differences between them?
  • Any performance gains?

Let me start off answering one by one the above questions and the findings I could spot out.

  1. When to choose each of those?

    There are actually no explicit scenarios as when to choose each of them. In fact, as you already know, you can choose the TryParse method if you need a safe conversion, i.e., No exceptions being thrown. But otherwise if you know the string value is just a number i.e., string str = “1?, then you can use any of 3 conversion methods. Although such scenarios are rare to occur in real world problems. So the standard guidelines always suggest to use Tryparse method.

  2. Why are there three ways?

    Based on different requirements, Microsoft created these 3 APIs for us to use. One of the requirement as already said above is safe conversion without needing to use Try-Catch-Finally at client side. And as per the name sake, Convert class is like a helper class which supports conversion for different types i.e., Int, char, bool, double, etc. Where as Int structure is specific to Int only and it can’t be a helper type here. If in case your code is only dealing with string to integer conversions, then you don’t have to use Convert helper class, because at this point it's a waste of memory for this static class, but this design is very much hypothetical.

  3. Are there any differences between them?

    Yes there are few difference between them in their working actually. Looking at the IL for each of these APIs, I came to know few interesting things:

    • Convert.Int32() first checks input value for null, if it is null then it returns 0.
    • Convert.Int32() internally calls Int32.Parse() method.
    • Int32.Parse() internally calls Number.ParseInt32() method.
    • Int32.Parse() does not check for null, since it directly calls Number.ParseInt32(), this method checks internally for null and throws ArgumentNullException.
    • Int32.TryParse() also does not directly check for null input, but instead it calls Number.TryParse() API which internally checks for null input and returns false if it is.
  4. Any performance gains?

    I have used the below code to do performance analysis:

    And the performance results I got are:

    As you can see, I have taken 5 output samples. It looks like Convert.ToInt32() method is performing much better here. But hold on, first this performance analysis is not accurate. The reason is that:

    1. Convert.ToInt32 uses Int32.Parse method internally.
    2. Due to extra checks for type safe conversions, TryParse() method is for sure known to be comparatively slow.
    3. Since Convert.ToInt32 first checks for null input and then calls Int32.Parse method, there is negligible delay in the performance figures.

    Hence considering all the above points, one need not really worry for performance factors in this case and rather focus on the benefits of each of these API as I already explained above.

So that’s all dear reader, I do hope you liked it.

Thanks. :)

P.S.: Your comments/votes are much appreciated.


Filed under: c#, CodeProject, dotnet Tagged: .NET, blog, c#, codeproject, dotnet, tips

License

This article, along with any associated source code and files, is licensed under The GNU Lesser General Public License (LGPLv3)

Share

About the Author

zenwalker1985
Software Developer (Senior) Siemens
India India
A .net developer since 4+ years, wild, curious and adventurous nerd.
 
Loves Trekking/Hiking, animals and nature.
 
A FOSS/Linux maniac by default Wink | ;)
 
An MVP aspirant and loves blogging -> https://adventurouszen.wordpress.com/
Follow on   Twitter

Comments and Discussions

 
GeneralThoughts PinprofessionalPIEBALDconsult27-Sep-13 19:26 
QuestionBenchmarks on Int.Parse(), Convert.ToInt32(), Int.TryParse() PinmemberMember 1024450327-Sep-13 19:04 
SuggestionPlease add the routine names to your timing results PinmemberL. Braun7-Nov-11 23:07 
GeneralRe: Please add the routine names to your timing results Pinmemberzenwalker19857-Nov-11 23:39 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.1411022.1 | Last Updated 5 Nov 2011
Article Copyright 2011 by zenwalker1985
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid