views:

62

answers:

1

I found that accessing Dictionary and Multi-Dimension array can be slow-- quite a puzzle since access time for dictionary and array is O(1).

This is my code

public struct StateSpace
{
public double q;
public double v;
public double a;
}

public class AccessTest
{
   public Dictionary<int, Dictionary<double,StateSpace>> ModeStateSpace;
   public double[,] eigenVectors;
   public void AccessJob(int n, double times)
  {
     var sumDisplacement = new double[6];
     for(int i=0; i< n; i++)
     {
       var modeDisplacement = ModeStateSpace[i][times].q;  //takes 5.81 sec
       for(int j=0; j<6; j++)
       {
                var eigenVector = eigenVectors[i, j];  //takes 5.69 sec
                sumDisplacement[i] += eigenVector*modeDisplacement ; //takes 1.06 sec        
       } 
     }
  } 



}

Notice the interesting part? The manipulation takes ~ 1 sec, but the accessing of dictionary and multi dimensional array takes ~5 sec!! Any idea why this is the case?

The n is not important here, and so is the absolute magnitude of the time needed for each operation. What is important is the ratio between the arithmetic operation and the dictionary lookup time.

Edit: I'm using Ants Profiler to do the profiling.

Note: I just simplified my actual code into something like this; the above code snippet has not been tested yet, but I'm fairly confident that I capture the gist of the problem with the above code snippet.

A: 

It is a known fact that jagged arrays are faster than multidimensional arrays in .NET (at least on windows):

ohadsc