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.
Be the first to rate this post
- Currently 0/5 Stars.
- 1
- 2
- 3
- 4
- 5