What is the fastest way to convert an object to a double? I'm at a piece of code right now, which reads:
var d = double.TryParse(o.ToString(), out d); // o is the Object...
First thoughts were to rewrite this as
var d = Convert.ToDouble(o);
but would that actually be faster?
EDIT: In addition to running the profile (by the way, I strongly recommend JetBrains dotTrace to any developer), I ran Reflector, and that helped me to come up with the following (more or less the relevant portion of the code):
if (o is IConvertible)
{
d = ((IConvertible)o).ToDouble(null);
}
else
{
d = 0d;
}
The original code double.TryParse()
executed in 140ms. The new code executes in 34ms. I'm almost certain that this is the optimization path I should take, but before I do that, does anyone see anything problematic with my "optimized" code? Thanks in advance for your feedback!
There are three ways to convert a String to double value in Java, Double. parseDouble() method, Double. valueOf() method and by using new Double() constructor and then storing the resulting object into a primitive double field, autoboxing in Java will convert a Double object to the double primitive in no time.
To convert double primitive type to a Double object, you need to use Double constructor. Let's say the following is our double primitive. // double primitive double val = 23.78; To convert it to a Double object, use Double constructor.
To convert a specified value to a double-precision floating-point number, use Convert. ToDouble() method. long[] val = { 340, -200}; Now convert it 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.
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