157 Tips for writing high-quality code to improve C # programs-suggest 4:tryparse better than parse

Source: Internet
Author: User

Suggest that 4:tryparse is better than parse.

If you look at all primitive types except string, you'll see that they all have two ways to transform the string to itself: Parse and TryParse. In the case of type double, the simplest prototypes of these two methods are:

 Public Static Double Parse (string  s)  publicstaticbool TryParse (string  out Double

The biggest difference between the two is that if the string format does not meet the requirements of the conversion, the parse method throws an exception, the TryParse method does not throw an exception, it returns false, and the result is set to 0.

In fact, the early FCL did not provide the TryParse method, then only the parse method can be called, if the transformation fails, you want to set the value to an initial value, and must catch the exception, the code is as follows:

    string NULL ;       Double D;       Try       {          = double.parse (str);      }       Catch (Exception ex)      {          0;      

It is important to note that the process of throwing an exception will result in a loss of performance (this is explained in detail in chapter 5th). This is what Microsoft's development team has noticed, so starting with. NET 2.0, the TryParse method for primitive types begins in the FCL. We might as well do an experiment where the code looks like this:

    Doublere; Longticks; Stopwatch SW=stopwatch.startnew ();  for(inti =1; I < +; i++)      {          Try{re=Double. Parse ("123"); }          Catch{re=0; }} SW.      Stop (); Ticks=SW.      Elapsedticks; Console.WriteLine ("Double. Parse () succeeded, {0} ticks", ticks); SW=stopwatch.startnew ();  for(inti =1; I < +; i++)      {          if(Double. TryParse ("123", outRE) = =false) {Re=0; }} SW.      Stop (); Ticks=SW.      Elapsedticks; Console.WriteLine ("Double. TryParse () succeeded, {0} ticks", ticks); SW=stopwatch.startnew ();  for(inti =1; I < +; i++)      {          Try{re=Double. Parse ("AAA"); }          Catch{re=0; }} SW.      Stop (); Ticks=SW.      Elapsedticks; Console.WriteLine ("Double. Parse () failed, {0} ticks", ticks); SW=stopwatch.startnew ();  for(inti =1; I < +; i++)      {          if(Double. TryParse ("AAA", outRE) = =false) {Re=0; }} SW.      Stop (); Ticks=SW.      Elapsedticks; Console.WriteLine ("Double. TryParse () failed with {0} ticks", ticks);

The output of the above code is:

    1. Double. Parse () succeeded, 6661 ticks
    2. Double. TryParse () success, 2886 ticks
    3. Double. Parse () failed, 2062347 ticks
    4. Double. TryParse () failed, 3379 ticks

As can be seen, the parse and TryParse methods, if executed successfully, are more efficient at an order of magnitude, even in this example (within a loop), TryParse is more efficient than parse. But if execution fails, the execution efficiency of parse is too low compared to tryparse.

We will provide this behavior of the TryParse method called type to provide TryParse mode. The TryParse pattern provides two methods for a type, assuming that the first method is declared as do, and the second method is declared as Trydo. The Do method throws an exception if an error occurs during execution, and the Trydo method returns a Boolean value, and the method execution failure returns false. If you want to get the actual return value from Trydo, you should provide an out parameter for the method.

However, it is not recommended to provide TryParse mode for all types, and it is recommended to use TryParse only when considering the apparent performance loss of the Do method.

Turn from: 157 recommendations for writing high-quality code to improve C # programs Minjia

157 Tips for writing high-quality code to improve C # programs-suggest 4:tryparse better than parse

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.