Double.TryParse or Convert.ToDouble - which is faster and safer?
I did a quick non-scientific test in Release mode. I used two inputs: "2.34523" and "badinput" into both methods and iterated 1,000,000 times.
Valid input:
Double.TryParse = 646ms
Convert.ToDouble = 662 ms
Not much different, as expected. For all intents and purposes, for valid input, these are the same.
Invalid input:
Double.TryParse = 612ms
Convert.ToDouble = ..
Well.. it was running for a long time. I reran the entire thing using 1,000 iterations and Convert.ToDouble
with bad input took 8.3 seconds. Averaging it out, it would take over 2 hours. I don't care how basic the test is, in the invalid input case, Convert.ToDouble
's exception raising will ruin your performance.
So, here's another vote for TryParse
with some numbers to back it up.
Faster alternative to Convert.ToDouble(string)
You can save about 10% by calling Double.TryParse
with specific cached instances of NumberStyles
and IFormatProvider
(i.e. CultureInfo
):
var style = System.Globalization.NumberStyles.AllowDecimalPoint;
var culture = System.Globalization.CultureInfo.InvariantCulture;
double.TryParse("1.34515", style, culture, out x);
Both Convert.ToDouble
and Double.Parse
or Double.TryParse
have to assume the input can be in any format. If you know for certain that your input has a specific format, you can write a custom parser that performs much better.
Here's one that converts to decimal
. Conversion to double
is similar.
static decimal CustomParseDecimal(string input) {
long n = 0;
int decimalPosition = input.Length;
for (int k = 0; k < input.Length; k++) {
char c = input[k];
if (c == '.')
decimalPosition = k + 1;
else
n = (n * 10) + (int)(c - '0');
}
return new decimal((int)n, (int)(n >> 32), 0, false, (byte)(input.Length - decimalPosition));
}
My benchmarks show this to be about 5 times faster than the original for decimal
, and up to 12 times if you use ints.
Fastest Way for Converting an Object to Double?
You must be doing a whole whopping lot of these in order to make any sense to spend any time on this. However, I am not here to judge:
So, your code is this:
if (o is IConvertible)
{
d = ((IConvertible)o).ToDouble(null);
}
else
{
d = 0d;
}
I wonder if you would be better off with this
IConvertible convert = o as IConvertible;
if (convert != null)
{
d = convert.ToDouble(null);
}
else
{
d = 0d;
}
Saves you the double cast.
C# double.TryParse with InvariantCulture returns unexpected result
It's not clear from your question what you expected. However, as far as what the code is doing, it's doing exactly what you told it to:
- Providing
NumberStyles.Any
tellsdouble.TryParse()
to allow any format, exceptAllowHexSpecifier
. This includes theAllowThousands
option. - Providing the
InvariantCulture
causes parsing to use the','
character as the thousands separator. - Parsing doesn't actually care where a thousands separator appears. I.e. it doesn't actually force the separator to be in the location where it would indicate a thousands-multiple digit.
So, when you ask it to parse "9,42"
, that text is interpreted using InvariantCulture
(i.e. ignoring your current culture of de-DE
), the ','
character is treated as a thousands separator (i.e. ignored for the purpose of computing the actual value), and you get the value 942
, just like you asked for.
If you don't want that result, you need to use different arguments for the call to double.TryParse()
. You would need to explain what you do want if you want advice on what arguments you should use. All we can say given the information currently in your question is what arguments you apparently don't want.
No overload for method 'TryParse' takes one argument error when using double.TryParse
double rad = Convert.ToDouble(radius);
if (double.TryParse(rad) == false)
should be
double rad;
if (!double.TryParse(radius, out rad))
Use !
(not) instead of == false
just as better coding practice.
Also, TryParse needs an out
value (It does the parsing, no need for Convert.ToDouble
and ... your Convert.ToDouble
will error if it's not parseable - bad!)
How to load data into program as double? (not string) in c# (window form application - visual studio)
Change these lines in your code to double.
string[] row = new string[values.Length];
for (int j = 0; j < values.Length; j++)
{
row[j] = values[j];
}
Instead
double[] row = new double[values.Length];
for (int j = 0; j < values.Length; j++)
{
row[j] = Convert.ToDouble(values[j]);
}
Related Topics
Sqldatasourceenumerator.Instance.Getdatasources() Does Not Locate Local SQL Server 2008 Instance
Implementing Hoey Shamos Algorithm with C#
Ef Code First - How to Set Identity Seed
How to Make a Background Worker Thread Set to Single Thread Apartment
Advantages to Using Private Static Methods
Token Based Authentication in ASP.NET Core (Refreshed)
Get List of Zero Reference Codes in Visual Studio
How Math.Pow (And So On) Actually Works
End of Central Directory Record Could Not Be Found
How to Target Attributes for a Record Class
Extremely Large Single-Line File Parse
Class List Keeps Printing Out as Class Name in Console
What Is the Best Practice for "Copy Local" and with Project References
Filter SQL Based on C# List Instead of a Filter Table
Executenonquery for Select SQL Statement Returning No Rows
How to Find Reason for Generic Gdi+ Error When Saving an Image
The Object Cannot Be Deleted Because It Was Not Found in the Objectstatemanager