Parse V. Tryparse

Parse v. TryParse

Parse throws an exception if it cannot parse the value, whereas TryParse returns a bool indicating whether it succeeded.

TryParse does not just try/catch internally - the whole point of it is that it is implemented without exceptions so that it is fast. In fact the way it is most likely implemented is that internally the Parse method will call TryParse and then throw an exception if it returns false.

In a nutshell, use Parse if you are sure the value will be valid; otherwise use TryParse.

What is better: int.TryParse or try { int.Parse() } catch

Better is highly subjective. For instance, I personally prefer int.TryParse, since I most often don't care why the parsing fails, if it fails. However, int.Parse can (according to the documentation) throw three different exceptions:

  • the input is null
  • the input is not in a valid format
  • the input contains a number that produces an overflow

If you care about why it fails, then int.Parse is clearly the better choice.

As always, context is king.

Double.Parse vs Double.TryParse

Double.TryParse([string to convert], out result);

TryParse function which accepts two arrangements the first one is the string you want to convert and the second is the output parameter with the result value but the method it self return true or false based on conversion if conversion completed successfully then return true if not it will return false

Double.Parse([string to convert]);  

Parse function don't return true or false based on conversion it will try to convert if success it will return the value converted if not it will throw exception so if you want to use Parse function you have to place it in try and catch clause to avoid exceptions

UPDATE the problem you facing in the string format it self

Here is a method that most closely resembles the code you've provided

public static decimal Parse(string input)
{
return decimal.Parse(Regex.Replace(input, @"[^\d.]", ""));
}

Here is an option that will support negative numbers, and will stop if it finds a second period value, thus reducing the number of strings it returns that are not valid decimal values. It also has a few other modifications not seen in the OP to handle additional cases your current code doesn't.

public static decimal Parse(string input)
{
return decimal.Parse(Regex.Match(input, @"-?\d{1,3}(,\d{3})*(\.\d+)?").Value);
}

What IDE to use for developing in Ruby on Rails on Windows?

Try both NetBeans and RadRails for maybe a week each, then you can find which works best for you. The best advice is to learn your tool. If you are not checking out something new about your editor, something that could potentially save you time (regexp, etc) then you are doing yourself a huge disservice.

I have been using Eclipse/Aptana/RadRails and unlike Gaius have been pretty happy with it.
I recommend the Eclipse IDE for Java Developers from Eclipse Downloads: http://www.eclipse.org/downloads/

Then grab Aptana Studio, following these instructions.

When Eclipse restarts Aptana will have a view, click on rad rails and you are good to go. Just make sure you have ruby installed already, or it becomes a pain to resolve.

Avoiding try-catch by using tryparse instead of parse

Yes, TryParse is faster.

However, this smells like a premature optimization to me, unless you expect Parse to be called in a tight loop with many invalid input strings.

You should choose not depending on speed but depending on requirements and what kind of data you expect to get. Also, consider another option: Convert.ToDouble

Parsing Performance (If, TryParse, Try-Catch)

Always use T.TryParse(string str, out T value). Throwing exceptions is expensive and should be avoided if you can handle the situation a priori. Using a try-catch block to "save" on performance (because your invalid data rate is low) is an abuse of exception handling at the expense of maintainability and good coding practices. Follow sound software engineering development practices, write your test cases, run your application, THEN benchmark and optimize.

"We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%" -Donald Knuth

Therefore you assign, arbitrarily like in carbon credits, that the performance of try-catch is worse and that the performance of TryParse is better. Only after we've run our application and determined that we have some sort of slowdown w.r.t. string parsing would we even consider using anything other than TryParse.

(edit: since it appears the questioner wanted timing data to go with good advice, here is the timing data requested)

Times for various failure rates on 10,000 inputs from the user (for the unbelievers):

Failure Rate      Try-Catch          TryParse        Slowdown
0% 00:00:00.0131758 00:00:00.0120421 0.1
10% 00:00:00.1540251 00:00:00.0087699 16.6
20% 00:00:00.2833266 00:00:00.0105229 25.9
30% 00:00:00.4462866 00:00:00.0091487 47.8
40% 00:00:00.6951060 00:00:00.0108980 62.8
50% 00:00:00.7567745 00:00:00.0087065 85.9
60% 00:00:00.7090449 00:00:00.0083365 84.1
70% 00:00:00.8179365 00:00:00.0088809 91.1
80% 00:00:00.9468898 00:00:00.0088562 105.9
90% 00:00:01.0411393 00:00:00.0081040 127.5
100% 00:00:01.1488157 00:00:00.0078877 144.6


/// <param name="errorRate">Rate of errors in user input</param>
/// <returns>Total time taken</returns>
public static TimeSpan TimeTryCatch(double errorRate, int seed, int count)
{
Stopwatch stopwatch = new Stopwatch();
Random random = new Random(seed);
string bad_prefix = @"X";

stopwatch.Start();
for(int ii = 0; ii < count; ++ii)
{
string input = random.Next().ToString();
if (random.NextDouble() < errorRate)
{
input = bad_prefix + input;
}

int value = 0;
try
{
value = Int32.Parse(input);
}
catch(FormatException)
{
value = -1; // we would do something here with a logger perhaps
}
}
stopwatch.Stop();

return stopwatch.Elapsed;
}

/// <param name="errorRate">Rate of errors in user input</param>
/// <returns>Total time taken</returns>
public static TimeSpan TimeTryParse(double errorRate, int seed, int count)
{
Stopwatch stopwatch = new Stopwatch();
Random random = new Random(seed);
string bad_prefix = @"X";

stopwatch.Start();
for(int ii = 0; ii < count; ++ii)
{
string input = random.Next().ToString();
if (random.NextDouble() < errorRate)
{
input = bad_prefix + input;
}

int value = 0;
if (!Int32.TryParse(input, out value))
{
value = -1; // we would do something here with a logger perhaps
}
}
stopwatch.Stop();

return stopwatch.Elapsed;
}

public static void TimeStringParse()
{
double errorRate = 0.1; // 10% of the time our users mess up
int count = 10000; // 10000 entries by a user

TimeSpan trycatch = TimeTryCatch(errorRate, 1, count);
TimeSpan tryparse = TimeTryParse(errorRate, 1, count);

Console.WriteLine("trycatch: {0}", trycatch);
Console.WriteLine("tryparse: {0}", tryparse);
}


Related Topics



Leave a reply



Submit