Reputation: 10145
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()
{
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.
Upvotes: 9
Views: 3107
Reputation: 15004
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.
Upvotes: -1
Reputation: 1502396
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?
Upvotes: 9