初始化每个班级成员时的性能问题



我认为这个问题是有关初始化的一般观点,并且已经回答了很多:

构造函数应该初始化类的所有数据成员?

但是,当我的班级有100名成员时,我没有发现有关可能的性能问题的任何事情,并且我用{}命令初始化每个成员,只是因为Eclipse警告我有关非初始化的成员:

在此构造函数中不初始化成员'foo'

我的问题:每次实例化此类时,每个成员[> 50]的班级初始化会导致性能问题?

更新:由于第一个注释:我一般都在问。Eclipse在我的项目中警告我9次在4堂课上分开!

在这里我的结果使用gcc。

我对其进行了测试[5次,并取了平均水平的班级成员计数,但班级有100'000'000实例化。

这有点棘手,因为我使用了最高的优化级别-O3,因此我必须避免编译器优化代码。

有100个班级成员:

Initialized class members:      4'484 msec
Not initialized class members:     50 msec

有25个班级成员:

Initialized class members:      1'146 msec
Not initialized class members:     50 msec // as expected it didn't change

有500个班级成员:

Initialized class members:     22'129 msec
Not initialized class members:     50 msec // as expected it didn't change

我的结论是:

在正常情况下存在 - - no 当所有类成员均被初始化时,出色的性能问题。在正常情况下,使用我的意思是,当有100'000'000迭代的函数时,成员初始化确实不计算。

正如评论中所述,好的设计不应该有那么多班级成员 - 我只是一般好奇。


PS:

我检查了汇编器列表,当然 - 在初始化的版本中,使用movq $0, 40(%rsp)初始化每个int成员 - 40是堆栈上的位置。


#include <stdlib.h>
#include <stdio.h>
#include <chrono>
#include <ctime>
#include <utility>
template<typename TimeT = std::chrono::microseconds>
class measure
{
public:
    template<typename F, typename ...Args>
    static typename TimeT::rep execution(F func, Args&&... args)
    {
        auto start = std::chrono::system_clock::now();
        func(std::forward<Args>(args)...);
        auto duration = std::chrono::duration_cast< TimeT> 
                                (std::chrono::system_clock::now() - start);
        return duration.count();
    }
};
class foo
{
   // for uninitialized version remove the {}
   size_t mainValue {};
   size_t classMember0 {};
   ...
   size_t classMember499 {};
public:
    foo( size_t value ) : mainValue (value + 4660) {};
    auto getMainValue() -> size_t { return mainValue; };
};
auto runCode( size_t iterationCount ) -> void
{
    size_t someValue {};
    for ( size_t j = 0 ; j < iterationCount ; ++j )
    {
        foo MyFoo (iterationCount);
        someValue += MyFoo.getMainValue();
    }
    printf( "Result=%ldn", someValue );   // that the whole code isn't optimized away...
}
int main( int argc, char * argv [] )
{
    if ( argc != 2 )
    {
        printf( "Usage: %s <Start-Value>n", argv [0] );
        return 0;
    }
    size_t variableValue = (size_t) atof( argv [1] );
    auto threadExecutionTime = measure<>::execution( [&] () { runCode( variableValue ); } );
    printf( "Total execution time was %.3f milliseconds. %s",
                threadExecutionTime / 1000. );
}

最新更新