初始化每个 class 成员时出现性能问题?

Performance issues when initializing each class member?

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

但是,当我的 class 有 100 个成员并且我使用 {} 命令初始化每个成员时,我没有发现任何关于可能的性能问题的信息,只是因为 Eclipse 发出警告我关于未初始化的成员:

Member 'foo' was not initialized in this constructor

我的问题:每次 class 中有很多成员 [>50] 的每个成员的初始化是否会导致性能问题? =]被实例化了?

更新: 由于第一条评论:我问的是一般情况。 Eclipse 在我的项目中警告我 9 次,分为 4 classes!

这是我的结果 运行 它是用 gcc 的。

我用不同数量的 class 成员测试了它 [5 次并取平均值],但 class.

有 100'000'000 个实例化

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

有 100 个 class 成员:

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

有 25 个 class 成员:

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

有 500 个 class 成员:

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

我的结论是:

有- 正常情况下 - 所有class 成员被初始化。在正常情况下 我的意思是当有一个函数 [与其他代码] 有 100'000'000 次迭代时,成员初始化真的不算数。

如评论中所述,一个好的设计不应该有这么多 class 成员 - 我只是一般好奇。


PS:

我检查了汇编程序列表 - 当然 - 实际上在初始化版本中 gcc 用 movq [=16=], 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=%ld\n", 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. );
}