본문 바로가기
프로그래밍/C & C++

[Effective C++] class를 사용할 때 초기화와 대입은 다르다

by 체리 2021. 12. 19.
반응형

class를 초기화 할 때 멤버 변수를 초기화 하는 형태를 보면 아래의 셋 중 하나를 선택하여 사용할 것이다.

 

1.  생성자에서 초기화 한다.

class TestClass
{
public:
    TestClass() : value(), str() // 여기서 초기화
    {
    	// 여기를 초기화에 사용하지 않음
    }

    TestEnum GetValue()
    {
        return value;
    }

    string str;

private:
    TestEnum value;
};

 

2. 생성자 내부에서 초기화 한다.

class TestClass2
{
public:
    TestClass2()
    {
        value = TestEnum::TYPE0;	// 이렇게 초기화
        str = "";					// 이렇게 초기화
    }

    TestEnum GetValue()
    {
        return value;
    }

    string str;

private:
    TestEnum value;
};

 

3. 선언에서 초기화한다.

class TestClass3
{
public:
    TestClass3()
    {
    }

    TestEnum GetValue()
    {
        return value;
    }

    string str = "";	// 이렇게 초기화

private:
    TestEnum value = TestEnum::TYPE0;	// 이렇게 초기화
};

 

차이가 있을까?

아래와 같이 test code를 작성하여 차이가 있을지 확인해 보았다.

추가로 const uint64_t MAX_LOOP = 100000000 이다.

std::chrono::system_clock::time_point start = std::chrono::system_clock::now();
for (uint64_t i = 0; i < MAX_LOOP; i++)
{
TestClass a;
}
std::chrono::system_clock::time_point end = std::chrono::system_clock::now();
cout << "elapsed time: "
    << std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count() << " ms" << endl;

start = std::chrono::system_clock::now();
for (uint64_t i = 0; i < MAX_LOOP; i++)
{
TestClass2 a;
}
end = std::chrono::system_clock::now();
cout << "elapsed time: "
    << std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count() << " ms" << endl;

start = std::chrono::system_clock::now();
for (uint64_t i = 0; i < MAX_LOOP; i++)
{
TestClass3 a;
}
end = std::chrono::system_clock::now();
cout << "elapsed time: "
    << std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count() << " ms" << endl;

 

사용하는 computer의 performance에 따라 결과는 다르겠지만 내 PC에서는 아래의 결과가 나타났다.

elapsed time: 616 ms => 1번의 경우
elapsed time: 1165 ms => 2번의 경우
elapsed time: 1330 ms => 3번의 경우

사실 의외였는데 1번과 2번은 차이가 날 수 있다고 생각은 했는데 2번과 3번의 차이가 사실 의외였다.

개발하는 code에서 LOC 때문에 그렇게 사용하는 것들이 있었는데 말이다.

 

결론적으로 1번의 초기화가 차지하는 시간이 매우 적으나 (100,000,000번 반복해서 저 시간이 나온 것이니까)

서로간의 차이가 분명하다는 것을 알게 되었다.

반응형

'프로그래밍 > C & C++' 카테고리의 다른 글

c++로 작성한 간단한 multi level queue  (0) 2022.01.08
c++로 작성한 간단한 pool  (0) 2022.01.08
[C/VC] 간단한 Critical Section 테스트  (0) 2011.03.06
struct 선언과 typedef  (0) 2007.03.31

댓글