类的构造及初始化效率对比

基础数据结构: 

    struct A
    {
        int a;
        int b;
        int c;
        int d;
        int e;
        int f;
        int g;
    };

初始化次数:const int MAX_LOOP_NUM = 100000000;

第一种方式: 无初始化

 struct A
    {
        A() 
        {
        }

        int a;
        int b;
        int c;
        int d;
        int e;
        int f;
        int g;
    };
View Code
        for(int index = 0; index < MAX_LOOP_NUM; ++index)
        {
            A a;
        }

运行时间:288ms

第二种方式:无初始化

    struct A
    {
        int a;
        int b;
        int c;
        int d;
        int e;
        int f;
        int g;
    };
View Code
        for(int index = 0; index < MAX_LOOP_NUM; ++index)
        {
            A a;
        }
View Code

运行时间: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

第五种方式:

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;
    };
View Code
        for(int index = 0; index < MAX_LOOP_NUM; ++index)
        {
            B b;
        }

运行时间:1790ms

第六种方式:

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;
    };
View Code
        for(int index = 0; index < MAX_LOOP_NUM; ++index)
        {
            C c;
        }

运行时间:1821

 

 

posted @ 2014-06-18 23:16  myfav  阅读(176)  评论(0编辑  收藏  举报