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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With