简体   繁体   English

将字符串数组转换为双数组的最快方法?

[英]Fastest way to convert string array to double array?

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? ...这实在是甜的......但今天,我决定切换回用于循环一个简单的解析在阵列双所有字符串,并没有太多令人惊讶的基准似乎倾向于for循环..所以我要切换回到基本的 for 循环?

Also, I want to know if there's a better type that can be used to store the splitted strings eg HashSet which may perform better during this conversion?另外,我想知道是否有更好的类型可用于存储拆分的字符串,例如HashSet在此转换过程中可能表现更好?

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

Unlike LINQ's .ToArray() , this pre-allocates a correctly-sized array and doesn't do any resizing.与 LINQ 的.ToArray() ,它预先分配了一个正确大小的数组,并且不进行任何调整大小。
This should be indistinguishable from a hand-rolled loop.这应该与手卷循环无法区分。

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.无法从用法推断方法“System.Array.ConvertAll(TInput[], System.Converter)”的类型参数。 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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM