类的构造及初始化效率对比
基础数据结构:
struct A { int a; int b; int c; int d; int e; int f; int g; };
初始化次数:const int MAX_LOOP_NUM = 100000000;
第一种方式: 无初始化
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
struct A { A() { } int a; int b; int c; int d; int e; int f; int g; };
for(int index = 0; index < MAX_LOOP_NUM; ++index) { A a; }
运行时间:288ms
第二种方式:无初始化
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
struct A { int a; int b; int c; int d; int e; int f; int g; };
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
for(int index = 0; index < MAX_LOOP_NUM; ++index) { A a; }
运行时间:293ms
第三种方式:
for(int index = 0; index < MAX_LOOP_NUM; ++index) { A a = {0}; }
运行时间:701ms
第四种方式:
for(int index = 0; index < MAX_LOOP_NUM; ++index) { A a; ::memset(&a, 0, sizeof(a)); }
运行时间:835ms
第五种方式:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
struct B { B() { a = 0; b = 0; c = 0; d = 0; e = 0; f = 0; g = 0; } private: int a; int b; int c; int d; int e; int f; int g; };
for(int index = 0; index < MAX_LOOP_NUM; ++index) { B b; }
运行时间:1790ms
第六种方式:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
struct C { C() : a(0), b(0), c(0), d(0), e(0), f(0), g(0) { } private: int a; int b; int c; int d; int e; int f; int g; };
for(int index = 0; index < MAX_LOOP_NUM; ++index) { C c; }
运行时间:1821