views:

124

answers:

4

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!

+3  A: 

Create a small test app using System.Diagnostics.Stopwatch and see which comes out as faster. Though I would argue this wouldn't make a worthwhile difference. I'd go for Convert.ToDouble purely for readability.

Adam
@Adam, good suggestion, I'll go for it. One point: I'm into the performance optimization phase of the project, so readability is going to slowly get deprecated in favor of sheer performance (that's where we're at... sigh!)
code4life
@code4life - its often good to optimize for performance, but don't do premature microoptimizations without fully understanding what needs to be optimized, it can just end up introducing harder to read, more error prone code while wasting your time.
CrimsonX
+1  A: 

First, if you really want to know which is faster, you should write a quick test (using the data you expect to be processing) and time each option. Without knowing what o is (or is likely to be) it's very hard to judge. I suspect you're not going to see much difference.

Second, unless you're calling this bit of code in an extremely time-critical portion of your code, and calling it thousands of time to boot, I doubt it really matters. Write good, clean code, then optimize.

Chris B.
And when you optimize, _always_ optimize based on a profiler.
jdmichal
@Chris: it was clean... but the code gets called over 40,000 times in one particular iteration. I'm profiling the code, and it was taking 140ms to execute, which in the project I'm working on is represents a big performance lag (believe it or not!). I'd like to make it go faster than that.
code4life
@jdmichal, absolutely agree.
code4life
+1  A: 

I tried the following methods.

  • double.TryParse
  • double.Parse
  • Convert.ToDouble

I used the following code.

public static void Main()
{
    string text = "3.14";
    var timer = new Stopwatch();
    timer.Start();
    for (int i = 0; i < 10000000; i++)
    {
        double d;
        d = Convert.ToDouble(text);
        //double.TryParse(text, out d);
        //d = double.Parse(text);
    }
    timer.Stop();
    Console.WriteLine("Time=" + timer.Elapsed.ToString());
    Console.ReadLine();
}

On my machine I saw these results. I averaged 3 different runs.

  • double.TryParse = 4.45 seconds
  • double.Parse = 4.45 seconds
  • Convert.ToDouble = 4.75 seconds

Of course, I used a string that was convertable. If the string is not convertable then I highly suspect double.TryParse will be the fastest by a long shot.

Brian Gideon
@Brian: did you mean seconds, or milliseconds?
code4life
@code4life - He probably meant seconds, due to the fact he did 10,000,000 conversions within that time period.
Nelson
@Nelson: thanks, got it!
code4life
Yeah, definitely seconds.
Brian Gideon
@Brian, thanks for the footwork! By the way, I did some more profiling and double.TryParse is not performant for objects purely because it only supports strings... hence objects need to be converted to string first then passed to the method, so 2 calls. Profiling shows it's a poor performer. But definitely outperforms when dealing only with strings (unfortunately not my case)
code4life
+1  A: 

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

IConvertable convert = o as IConvertable

if (convert != null)
{
  d = convert.ToDouble(null);
}
else
{
  d = 0d;
}

Saves you the double cast.

Flory
40,000 calls to this one function... that's the reason!
code4life
Great, well check out if it would be better without doing the double cast. Can't see how it wouldn't be.
Flory
@Flory, thanks for the recommendation. I'm going to take it, it makes sense.
code4life
Which is true for me every once in a great while!
Flory