C++ 初始化列表初始化列表性能问题的简单的探索

C++ 初始化列表性能问题的简单的探索


从概念上来讲,构造函数的执行可以分成两个阶段,初始化阶段和计算阶段,初始化阶段先于计算阶段

在执行构造函数时,如果没有给定初始值,那系统就会自动进行初始化。

#include <stdlib.h>
#include <iostream>
#include <string>

class myclass
{
public:
    int num_i;
    float num_f;
    double num_d;
    char chr;
    std::string str;
};

int main()
{
    myclass test;
    std::cout << test.chr << std::endl;
    std::cout << test.str << std::endl;
    std::cout << test.num_i << std::endl;
    std::cout << test.num_f << std::endl;
    std::cout << test.num_d << std::endl;
    

    system("pause");
}


初始化列表是在初始化阶段对成员变量进行复制,因此使用初始化列表比构造函数更加快速。

可以通过比较使用初始化列表和不适用初始化列表的构造函数的执行时间来进行测试。

 

不使用初始化列表:

#include <stdlib.h>
#include <iostream>
#include <string>
#include <time.h>
#include <Windows.h>

class myclass
{
public:
    myclass(std::string *str) 
    {
        mystr = new std::string[1000];
        mystr = str;
    }
private:
    std::string *mystr;
};

int main()
{

    time_t start,end;

    std::string *str = new std::string[1000];
    for (int i = 0; i < 1000; i++)
        str[i] = "hello";

    start = clock();
    myclass n_class(str);
    end = clock();

    std::cout << "函数执行时间:" <<(end - start)*1000/CLOCKS_PER_SEC;//精确到毫秒
    std::cout << "\n";
    system("pause");
}

使用初始化列表:

#include <stdlib.h>
#include <iostream>
#include <string>
#include <time.h>
#include <Windows.h>

class myclass
{
public:
    myclass(std::string *str) :mystr(new std::string[1000])
    {
        mystr = str;
    }
private:
    std::string *mystr;
};

int main()
{

    time_t start,end;

    std::string *str = new std::string[1000];
    for (int i = 0; i < 1000; i++)
        str[i] = "hello";

    start = clock();
    myclass n_class(str);
    end = clock();

    std::cout << "函数执行时间:" <<(end - start)*1000/CLOCKS_PER_SEC;//精确到毫秒
    std::cout << "\n";
    system("pause");
}

由执行的结果可以看出,在使用初始化列表函数执行的更加快速。

 

posted @ 2017-07-06 14:56  青柯  阅读(343)  评论(0编辑  收藏  举报