问题
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