Is there a faster way to loop through thousands of items?

拥有回忆 提交于 2019-12-23 12:17:18

问题


Say I have a byte array with 100,000 bytes in it. I want to convert each byte into its textual representation of itself. For example:

byte[] b = new byte[55000];

for(int i = 0; i < b.Length; i++)
{
Console.WriteLine(ConvertToString(b[i]));
}

The above code takes around 35 seconds to complete, is there some way I could cut that down to around 5 seconds?


回答1:


As mentioned in my comment I would suggest removing the Console.WriteLine() method. I would also suggest that it be avoided in loops. Typically if you want to see what is being processed you would use either the Debug.WriteLine() (MSDN) or set a breakpoint (even a conditional breakpoint if you have a specific case that isn't working right). If you need to return the data then again i would suggest using a string builder:

byte[] b = new byte[55000];
StringBuilder myStringBuilder = new StringBuilder();

for(int i = 0; i < b.Length; i++)
{
    myStringBuilder.AppendLine(ConvertToString(b[i]));
}
Console.Write(myStringBuilder.ToString());



回答2:


one thing I fond is Write a Parallel.For Loop with might do faster thing than right now..

    static void Main()
    {
        int[] nums = Enumerable.Range(0, 1000000).ToArray();
        long total = 0;

        // Use type parameter to make subtotal a long, not an int
        Parallel.For<long>(0, nums.Length, () => 0, (j, loop, subtotal) =>
        {
            subtotal += nums[j];
            return subtotal;
        },
            (x) => Interlocked.Add(ref total, x)
        );

        Console.WriteLine("The total is {0}", total);
        Console.WriteLine("Press any key to exit");
        Console.ReadKey();
    }



回答3:


Profile your code to see what method is taking the most time. Focus your optimization efforts on that method.



来源:https://stackoverflow.com/questions/9155921/is-there-a-faster-way-to-loop-through-thousands-of-items

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!