C#:将int []转换为字符串的最有效方法

时间:2012-11-18 13:00:27

标签: c# arrays string optimization int

我知道这类问题已经多次回答过了。虽然我已经找到了很多可能的答案,但它们仍然无法解决我的问题,实现了将整数数组转换为单个字符串的最快方法。我有例如:

int[] Result = new int[] { 1753387599, 1353678530, 987001 }

我希望它反转,所以我认为最好在进一步的代码之前加上

Array.Reverse(Result);

虽然我没有从最后迭代,但它相当于反转,因为我从末尾调用元素。所以我已经这样做了。只是为了让你知道 - 如果你能想到除我之外的任何其他解决方案,我建议使用这个Array.Reverse,因为必须颠倒解决方案。 我一直只关心一个数字的最后9位数 - 所以就像模数1 000 000 000.这是我想得到的:

987001|353678530|753387599

分隔符现在就清楚了。我编写了自己的函数,比使用.ToString()快了约50%。 tempint - int数组的当前元素, StrArray - 一个字符串数组。使用StringBuilder或求和是不值得的 字符串,所以最后我只是加入AnswerArr的元素来获得结果。 IntBase - 一个包含1000个元素的数组,字符串中的数字从“000”到“999”,索引为0到999。

    for (i = 0; i < limit; i++)
    {
    //Some code here

    j = 3 * (limit - i);

    //Done always
    StrArray[j - 1] = IntBase[tempint % 1000];

    if (tempint > 999999) 
    {
        //Done in 99/100 cases
        StrArray[j - 2] = IntBase[tempint % 1000000 / 1000]; 
        StrArray[j - 3] = IntBase[tempint % 1000000000 / 1000000];
    }
    else
    {
        if (tempint > 999) 
        {
            //Done just once
            StrArray[j - 2] = IntBase[tempint % 1000 / 1000];
        }
    }
    }
    //Some code here

    return string.Join(null, StrArray);

在这部分之前有很多计算,它们的完成速度非常快。虽然一切都在714毫秒,但没有求和整数,它只有337毫秒。

提前感谢您的帮助。

祝你好运, 伦道夫

2 个答案:

答案 0 :(得分:4)

更快?效率最高?我不确定,你应该尝试一下。但转换的简单方法

int[] Result = new int[] { 1753387599, 1353678530, 987001 };
var newstr = String.Join("|", Result.Reverse().Select(i => i % 1000000000));

答案 1 :(得分:1)

对于大多数情况,我会建议L.B的答案。但是,如果你的效率最高,那么我的建议是:

  • 您可以从最后迭代数组,因此无需调用任何类型的Reverse
  • IntBase[tempint % 1000000 / 1000]IntBase[tempint % 1000]相同,因为除法的优先级高于模数
  • 我打赌整个IntBase中间步骤正在大大减缓你的速度

我的建议是这样的 - 就像L.B的代码一样,但强制性和略微优化。

var sb = new StringBuilder();
var ints; // Your int[]

// Initial step because of the delimiters.
sb.Append((ints[ints.Length - 1] % 1000000000).ToString());

// Starting with 2nd last element all the way to the first one.
for(var i = ints.Length - 2; i >= 0; i--)
{
    sb.Append("|");
    sb.Append((ints[i] % 1000000000).ToString());
}

var result = sb.ToString();