為什么.NET中的多維數(shù)組比普通數(shù)組慢?我試圖用一個(gè) 盤陀今天的多維數(shù)組,當(dāng)我注意到它的性能并不像我預(yù)期的那樣。使用單維數(shù)組和手動(dòng)計(jì)算索引要比使用2D數(shù)組快得多(幾乎兩倍)。我使用1024*1024數(shù)組(初始化為隨機(jī)值)編寫了一個(gè)測試 ,進(jìn)行了1000次迭代,我在我的機(jī)器上得到了以下結(jié)果:sum(double[], int): 2738 ms (100%)sum(double[,]): 5019 ms (183%)sum(double[][]): 2540 ms ( 93%)這是我的測試代碼:public static double sum(double[] d, int l1) {
// assuming the array is rectangular
double sum = 0;
int l2 = d.Length / l1;
for (int i = 0; i < l1; ++i)
for (int j = 0; j < l2; ++j)
sum += d[i * l2 + j];
return sum;}public static double sum(double[,] d) {
double sum = 0;
int l1 = d.GetLength(0);
int l2 = d.GetLength(1);
for (int i = 0; i < l1; ++i)
for (int j = 0; j < l2; ++j)
sum += d[i, j];
return sum;}public static double sum(double[][] d) {
double sum = 0;
for (int i = 0; i < d.Length; ++i)
for (int j = 0; j < d[i].Length; ++j)
sum += d[i][j];
return sum;}public static void Main() {
Random random = new Random();
const int l1 = 1024, l2 = 1024;
double[ ] d1 = new double[l1 * l2];
double[,] d2 = new double[l1 , l2];
double[][] d3 = new double[l1][];
for (int i = 0; i < l1; ++i) {
d3[i] = new double[l2];
for (int j = 0; j < l2; ++j)
d3[i][j] = d2[i, j] = d1[i * l2 + j] = random.NextDouble();
}
//
const int iterations = 1000;
TestTime(sum, d1, l1, iterations);
TestTime(sum, d2, iterations);
TestTime(sum, d3, iterations);}進(jìn)一步研究表明,第二種方法的IL比第一種方法大23%。(代碼大小68比52)這主要是由于呼叫System.Array::GetLength(int)。編譯器還發(fā)出呼吁Array::Get為盤陀多維數(shù)組,而它只需要ldelem簡單的數(shù)組。所以我想知道,為什么通過多維數(shù)組訪問比普通數(shù)組更慢?我會(huì)假設(shè)編譯器(或JIT)會(huì)做類似于我在第一種方法中所做的事情,但事實(shí)并非如此。你能不能幫助我理解為什么會(huì)發(fā)生這種情況?
- 3 回答
- 0 關(guān)注
- 698 瀏覽
添加回答
舉報(bào)
0/150
提交
取消