I'm working with CT images, so I need to operate 3D arrays a lot, but found that C# deals with arrays extremely slow. I wrote a simple BFS test, based on https://stackoverflow.com/a/1056091:
struct Vector
{
public int X, Y, Z;
}
int width = 512, height = 512, depth = 200;
public static int bfs(int[, ,] matrix)
{
bool[, ,] visited = new bool[width, height, depth];
int sum = 0;
Queue<Vector> queue = new Queue<Vector>();
queue.Enqueue(new Vector { X = 0, Y = 0, Z = 0 });
while (queue.Count > 0)
{
Vector c = queue.Dequeue();
int cx = c.X;
int cy = c.Y;
int cz = c.Z;
sum += matrix[cx, cy, cz];
int x, y, z;
if ((x = cx - 1) >= 0 && !visited[x, cy, cz])
{ queue.Enqueue(new Vector { X = x, Y = cy, Z = cz }); visited[x, cy, cz] = true; }
if ((y = cy - 1) >= 0 && !visited[cx, y, cz])
{ queue.Enqueue(new Vector { X = cx, Y = y, Z = cz }); visited[cx, y, cz] = true; }
if ((z = cz - 1) >= 0 && !visited[cx, cy, z])
{ queue.Enqueue(new Vector { X = cx, Y = cy, Z = z }); visited[cx, cy, z] = true; }
if ((x = cx + 1) < width && !visited[x, cy, cz])
{ queue.Enqueue(new Vector { X = x, Y = cy, Z = cz }); visited[x, cy, cz] = true; }
if ((y = cy + 1) < height && !visited[cx, y, cz])
{ queue.Enqueue(new Vector { X = cx, Y = y, Z = cz }); visited[cx, y, cz] = true; }
if ((z = cz + 1) < depth && !visited[cx, cy, z])
{ queue.Enqueue(new Vector { X = cx, Y = cy, Z = z }); visited[cx, cy, z] = true; }
}
return sum;
}
public static void TestTime<T, TR>(Func<T, TR> action, T obj, int iterations)
{
Stopwatch stopwatch = Stopwatch.StartNew();
for (int i = 0; i < iterations; ++i)
action(obj);
Console.WriteLine(action.Method.Name + " took " + stopwatch.Elapsed);
}
static void Main(string[] args)
{
Random random = new Random();
int[, ,] m1 = new int[width, height, depth];
for (int x = 0; x < width; ++x)
for (int y = 0; y < height; ++y)
for (int z = 0; z < depth; ++z)
m1[x, y, z] = random.Next();
const int iterations = 1;
TestTime<int[, ,], int>(bfs, m1, iterations);
TestTime<int[, ,], int>(bfs, m1, iterations);
}
This takes ~23 secs (one iteration). Compiled with VS2012, "Release"d, optimized. Tried to write analogous C++ code (with stack allocated arrays), it takes ~0,08sec. DFS (with Stack instead of Queue) runs slower. 1D or jagged arrays give almost same results. I should note that continuous access (as in Why are multi-dimensional arrays in .NET slower than normal arrays?) runs fine, 100 iterations of [512x512x200] array in ~26 secs.
Why non-continuous array access is so slow in C#? Is there any way to speed it up?