20

I've been having to deal lately with conversion of large string arrays to number arrays and I'm wondering what the fastest method out there for this really is.

At first I adopted:

double[] doubles = sarray.Split(',').Select(Double.Parse).ToArray();

...which is really sweet... But today, I decided to switch back to a simple for loop to parse all strings in array to Double and not too surprisingly the benchmark seemed to favour the for loop.. so should I switch back to a basic for loop?

Also, I want to know if there's a better type that can be used to store the splitted strings e.g. HashSet which may perform better during this conversion?

3
  • 3
    A simple loop will always out-perform a Linq query. Commented Mar 1, 2012 at 21:51
  • 1
    The title says int but in the code you are using double. Which is it? Commented Mar 1, 2012 at 21:56
  • sorry, I don't know if it's only me but I have this problem of thinking of numbers as *int. :) Commented Mar 1, 2012 at 21:59

2 Answers 2

52
Array.ConvertAll(sarray.Split(','), Double.Parse);

Unlike LINQ's .ToArray(), this pre-allocates a correctly-sized array and doesn't do any resizing.
This should be indistinguishable from a hand-rolled loop.

Sign up to request clarification or add additional context in comments.

2 Comments

Would this be faster than the for loop?
Wow! I always forget about the Array class! That was awesome. Thanks!!
14

When I used:

double[] doubles = Array.ConvertAll(sarray.split(','), Double.Parse);

I got this error:

The type arguments for method 'System.Array.ConvertAll(TInput[], System.Converter)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

But it worked when I did this:

double[] doubles = Array.ConvertAll(sarray.split(','), new Converter<string, double>(Double.Parse));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.