Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding try-catch by using tryparse instead of parse

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?

like image 925
petko_stankoski Avatar asked Jan 19 '26 11:01

petko_stankoski


1 Answers

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

like image 149
Zdeslav Vojkovic Avatar answered Jan 21 '26 01:01

Zdeslav Vojkovic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!