12

Which is the fastest method for convert an string's array ["1","2","3"] in a int's array [1,2,3] in c#?

thanks

Luca Romagnoli
  • 12,145
  • 30
  • 95
  • 157

7 Answers7

24
string[] arr1 = {"1","2","3"};
int[] arr2 = Array.ConvertAll(arr1, s => int.Parse(s));

The use of Array.ConvertAll ensures (unlike LINQ Select/ToArray) that the array is initialized at the right size. You can possible get a shade quicker by unrolling, but not much:

int[] arr2 = new int[arr1.Length];
for(int i = 0 ; i < arr1.Length ; i++) {
    arr2[i] = int.Parse(arr[i]);
}

If you need something faster still (perhaps bulk file/data handling), then writing your own parse might help; the inbuilt one handles a lot of edge-cases - if your data is simpler you really can cut this down a bit.


For an example of an alternative parser:

    public static unsafe int ParseBasicInt32(string s)
    {
        int len = s == null ? 0 : s.Length;
        switch(s.Length)
        {
            case 0:
                throw new ArgumentException("s");
            case 1:
                {
                    char c0 = s[0];
                    if (c0 < '0' || c0 > '9') throw new ArgumentException("s");
                    return c0 - '0';
                }
            case 2:
                {
                    char c0 = s[0], c1 = s[1];
                    if (c0 < '0' || c0 > '9' || c1 < '0' || c1 > '9') throw new ArgumentException("s");
                    return ((c0 - '0') * 10) + (c1 - '0');
                }
            default:
                fixed(char* chars = s)
                {
                    int value = 0;
                    for(int i = 0; i < len ; i++)
                    {
                        char c = chars[i];
                        if (c < '0' || c > '9') throw new ArgumentException("s");
                        value = (value * 10) + (c - '0');
                    }
                    return value;
                }
        }
    }
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
15
var values = new string[] { "1", "2", "3" };
values.Select(x => Int32.Parse(x)).ToArray();
Sly
  • 15,046
  • 12
  • 60
  • 89
  • 1
    Int32.TryParse is faster the Int32.Parse – Denis Palnitsky Jun 21 '10 at 10:00
  • 1
    And this doesn't actually give an array... and isn't the "fastest" (question) way of populating such an array. But other than that... – Marc Gravell Jun 21 '10 at 10:02
  • 1
    How is this the accepted answer when a) it returns a different data structure to what you asked for and b) Marc Gravell's answer is an order of magnitude better than ever other one on here? – Ed James Jun 21 '10 at 10:02
  • you can write `values.Select(Int32.Parse);` why to add that lambda wrapper? – Andrey Jun 21 '10 at 10:07
  • It is accepted, but the person felt it was the correct answer. It is not about better/worst, right/wrong, or whatever. Maybe the question was just worded incorrectly? – AMissico Jun 21 '10 at 10:16
  • @AMissico I'm not sure that's true: this site is meant to be a QA site, not a forum, the correct answer should be the one that answers the question correctly, i.e. the best answer. – Ed James Jun 21 '10 at 10:18
  • @Ed Woodcock: Yes, but Marc Gravell's answer will become the obvious correct answer, so others will benefit from this question regardless of the accepted answer. – AMissico Jun 21 '10 at 10:22
  • @Ed Woodcock: Just look at all the non-ConvertAll answers with up votes. – AMissico Jun 21 '10 at 10:24
  • @AMissico but it's not set as the accepted answer to the question (when it's clearly the best answer) which can and probably will confuse anyone new to the site. There's nothing wrong with saying the non-convertall answers are good answers, but I'd have the same problem if any of them were marked as 'correct' (even my own answer) – Ed James Jun 21 '10 at 10:27
  • @Ed Woodcock: User has no activity since accepting answer. They may change the accepted answer once they return (or maybe not). Regarding confusion, if a newbie get confused, I do not think they would (or should) be a programmer. – AMissico Jun 21 '10 at 14:58
2

I suggest to iterate and int.TryParse()

Which one is faster in processing and conversion int.Parse(), int.TryParse(), Convert.Int32()

See Microsoft comparison of Parse , TryParse and ConvertTo

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
Denis Palnitsky
  • 18,267
  • 14
  • 46
  • 55
2

I'd probably do:

string[] array = new[] { "1", "2" }; // etc.
int[] ints = array.Select(x => int.Parse(x)).ToArray();

if I could guarantee that the data would be only integers.

if not:

string[] array = new[] { "1", "2" }; // etc.
List<int> temp = new List<int>();
foreach (string item in array)
{
    int parsed;
    if (!int.TryParse(item, out parsed))
    {
         continue;
    }

    temp.Add(parsed);
}

int[] ints = temp.ToArray();
Ed James
  • 10,385
  • 16
  • 71
  • 103
1

iterate and convert.

this. __curious_geek
  • 42,787
  • 22
  • 113
  • 137
1

The is no fast way I know but you can use a "short way":

var numbers = new[] {"1", "2", "3"};

var result = numbers.Select(s => int.Parse(s));
int[] resultAsArray = result.ToArray();

And if you use PLink you get to compute the values in parallel.

Dror Helper
  • 30,292
  • 15
  • 80
  • 129
1
string[] arr = new string[]{ "1", "2", "3" };
int[] lss = (from xx in arr
             select Convert.ToInt32(xx)).ToArray();
abatishchev
  • 98,240
  • 88
  • 296
  • 433
user374191
  • 121
  • 9