3

In a lot of places in my code I have this:

try
{
    price = double.Parse(sPrice.Replace(",", "."), CultureInfo.InvariantCulture);
}
catch
{
    price  = 0;
}

I read somewhere that if the exception is thrown in the try block, it takes a lot of time being caught.

So, I'd like to use tryparse instead of parse, like this:

if (!double.TryParse(sPrice, out price))
{
     price  = 0;
}

Is this a good practice? Will it take less time?

4
  • 1
    You could benchmark it yourself. As for good practice, well. That's entirely subjective but I prefer tryparse-methods, myself. =) Commented Mar 5, 2013 at 9:27
  • Yes it will indeed save execution time Commented Mar 5, 2013 at 9:28
  • possible duplicate of Parse v. TryParse Commented Mar 5, 2013 at 9:29
  • You should only do this if failure is expected to happen sometimes, e.g. when parsing user-typed text. You should not do this when parsing stuff which is supposed to be correct. Otherwise you are hiding errors. Commented Mar 5, 2013 at 9:31

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

How do you mean premature optimization?
How do you know it is too slow? :) In most cases, overhead introduced by exception handling is negligible compared to rest of the processing so it makes no sense to optimize the code for speed. The readability/ease of maintenance are quite often better optimization goals, IMO.
1

Two benefits I feel of using TryParse

  1. It is fast as compared to try.. catch...
  2. You will always have value in your variable, either the one you want to assign or the default one. So you can use your variable directly once it is passed to TryParse

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.