Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest Way for Converting an Object to Double?

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!

like image 856
code4life Avatar asked Jul 02 '10 16:07

code4life


People also ask

How do you convert an object to a double value?

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.

How do you convert double to double?

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.

How do I convert an int to a double in C#?

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.


1 Answers

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.

like image 153
Flory Avatar answered Oct 13 '22 03:10

Flory