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

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

  1. 访问效率比较(在vscode下gcc编译环境下,进行10亿次访问)
    • 静态声明:一维数组 = 二维数组 > 类对象数组 = 类对象嵌套数组
    • 动态声明:访问速度全部相等
  2. 结论:
    • N 维静态数组访问速度是最快的,并且可以使用维度进行逻辑划分,比相同条件下的类对象数组快约23%
    • 动态申请下访问速度都一样。如果比较大无法存储在栈中,动态申请的N 维度数组与类对象数组和类嵌套数组速度相同。
    • 使用一维数组和维度变量计算模拟N维度数组的访问方式是最慢的,因为通过维度变量计算具体的位需要很大的开销(比N维数组直接访问多了3倍)
    #include <stdint.h>
    #include <stdatomic.h>
    #include <iostream> 
    #include <map>
    #include <stack>
    #include <queue>
    #include <algorithm>
    #include <vector>
    #include <mutex>
    #include<time.h>
    #include<stdio.h>
    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;
    }
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

逆羽飘扬

如果有用,请支持一下。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值