开发者

Accessing Dictionary and Multi-Dimension Array is Slow

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 modeDisplacemen开发者_运维技巧t = 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.


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

  • Why are multi-dimensional arrays in .NET slower than normal arrays?

  • What are the differences between a multidimensional array and an array of arrays in C#?

    so maybe try a jagged array instead

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜