一维数组和二维数组的访问效率比较(包含类对象数组)

一维数组和二维数组的访问效率

  1. 访问效率比较(在vscode下gcc编译环境下,进行10亿次访问)
    • 静态声明:一维数组 = 二维数组 > 类对象数组 = 类对象嵌套数组
    • 动态声明:访问速度全部相等
  2. 结论:
    • N 维静态数组访问速度是最快的,并且可以使用维度进行逻辑划分,比相同条件下的类对象数组快约23%
    • 动态申请下访问速度都一样。如果比较大无法存储在栈中,动态申请的N 维度数组与类对象数组和类嵌套数组速度相同。
    • 使用一维数组和维度变量计算模拟N维度数组的访问方式是最慢的,因为通过维度变量计算具体的位需要很大的开销(比N维数组直接访问多了3倍)
    #include 
    #include 
    #include  
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include
    #include
    using namespace std;
    
    class Integer {
      public:
        int i;
        Integer(){i = 9;}
        int get_i(){
          return i;
        }
    };
    
    class Test{
      public:
        Integer instance[2];
        void addr(){
          cout << &instance[0] << " " <<  &instance[1] << " " << sizeof(int);
          // 相差4个字节,即1个int。所以类对象数组和
        }
    };
    
    int main (){
      // 动态申请下,类对象和一维数组访问速度的比较。
      // 结论:10亿访问速度相差波动1%以内,应该都是通过指针索引数组的方式,即底层访问速度相同
      // Integer* i = new Integer[4];
      // int* ii = new int[4];
    
      // 静态访问下,类对象和一维数组访问速度的比较。
      // 结论:两者访问方式不同,数组访问比类对象访问快了约23%
      // Integer i[4];
      // int ii[4];
    
    
      // 结论:静态访问下,二维数组,类对象数组和一维数组访问速度均
      // int i[2][2];
      // Test ii[2];
    
      // 结论:动态申请下,类嵌套对象、二维数组和动态下的一维数组访问速度均相同
      Test *tt = new Test[2];
      // 计时
      double dur;
      clock_t start,end;
      start = clock();
    
      for (int j = 0; j < 1000000000; ++j)  {
        for (int g = 0; g < 4; ++g){
          
           int p = tt[1].instance[1].i;
          // int p = i[3].i
        }
          //
      }
      end = clock();
      dur = (double)(end - start);
      printf("Use Time:%f\n",(dur/CLOCKS_PER_SEC));
      cout << endl;
      return 0;
    }
    

你可能感兴趣的:(笔记,性能优化)