Johnny posted on October 8, 2008 04:20

I have recently been reviewing a lot of code from other developers. I always try to keep an open mind so if I see something another developer has done that I do a different way I am curious to which is the better way. Of course "better" is a very abstract word so I decided to look at it from a performance perspective since performance can be concretely measured.

The code that caught my attention was:

 bool isNotify = Convert.ToBoolean(ConfigurationManager.AppSettings["SomeSettingGoesHere"]);

normally I would have written the above code like this:

 bool isNotify = bool.Parse(ConfigurationManager.AppSettings["SomeSettingGoesHere"]));

Convert is a little more flexible than Parse but which one performs better? I did some test...

The Test:

In a method called TestParse() I looped 1 million times creatint an instance of a string, string varA = "true". I then Parsed that string using bool varB = bool.Parse(varA).Prior to starting the loop and after completing the loop I set a variable equal to the DateTime.Now and returns the TimeSpan between the two DateTimes and displayed it in milliseconds.

I also created a method called TestConvert and did the exact same thing except instead of using bool.Parse(varA) I used Convert.ToBoolean(varA).

I ran both of these methods from a console app and displayed the results:

 



as you can see the Parse method completed significantly quicker than the Convert method. I ran similar test of different types such as Int32 and decimal and received similar results.

Posted in: Programming  Tags:

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


Related posts

Comments


us Todd
October 8. 2008 06:27
That's pretty interesting. You have confirmed what I always thought was the case. I remember reading forum posts arguing about this in this past. I was always on the side opposite the Convert crowd.

That's a 13.5% performance difference.

Thanks for doing the test.



Search Blog Post

Follow me on

Twitter Updates

    Recent Comments

    Disclaimer
    The opinions expressed herein are my own personal opinions.

    © Copyright 2010 Johnny Can't Code