Fastest way to fill a matrix with Random bytes
I want to fill an array with random values. The code I wrote is this one:
public class PersonalityMap
{
const int size = 16;
byte[,] fullMap = new byte[size, size];
/// <summary>
/// Generates a random map
/// </summary>
public PersonalityMap()
开发者_C百科 {
Random random = new Random();
byte[] row = new byte[size];
for (int i = 0; i < size; i++)
{
random.NextBytes(row);
for (int j = 0; j < size; j++)
fullMap[i, j] = row[j];
}
}
}
But I feel there's a way to do it faster.
Well, you could create one single-dimensional array, fill that, and then copy it with Buffer.BlockCopy:
Random random = new Random();
byte[] row = new byte[size * size];
random.NextBytes(row);
Buffer.BlockCopy(row, 0, fullMap, 0, size * size);
However, before you try to optimize even further - just how quick do you need this to be? Have you benchmarked your application and determined that this is the bottleneck of your application?
Jagged arrays (arrays of arrays) are consider faster than multidimensional arrays, but you will get speed up of a few ms. Is this worth it?
This optimization is not worth to spend your time on it.
精彩评论