Reputation: 10723
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?
Upvotes: 3
Views: 329
Reputation: 14591
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
Upvotes: 3
Reputation: 8990
Two benefits I feel of using TryParse
try.. catch...
Upvotes: 1