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

Let's say I have a byte array with 100,000 bytes. I want to convert every byte into its textual representation of myself. For instance:

byte[] b = new byte[55000];

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

The above code takes about 35 seconds to complete, is there any way to reduce this to about 5 seconds?

+5
source share
3 answers

, Console.WriteLine(). , . , , , Debug.WriteLine() (MSDN), ( , ). , :

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());
+4

Parallel.For Loop, - , ..

    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 which method uses the most time. Focus your optimization efforts on this method.

-1
source

All Articles