5

Which one of the following is preferred/more efficient?

  • Initialization list:

    class Trial {
    private:
        std::vector<int> _vec;
    
    public:
        Trial(size_t length) : _vec(length) {
        }
    };
    
  • Resize:

    class Trial {
    private:
        std::vector<int> _vec;
    
    public:
        Trial(size_t length) {
            _vec.resize(length);
        }
    };
    

I've seen both in production code, but I've also heard that if you can delegate some work to the compiler, you should, so I always preferred the first one.

Is one of them better than the other?

cpplearner
  • 13,776
  • 2
  • 47
  • 72
ChrisG
  • 221
  • 4
  • 12
  • The first one may be more canonical. The optimizer will make these two versions similar at assembly level. So the answers will be opinion based. – Oliv Aug 22 '18 at 09:56
  • 2
    [Member initialization lists are generally preferred.](https://stackoverflow.com/questions/926752/why-should-i-prefer-to-use-member-initialization-list) – Ben Jones Aug 22 '18 at 14:42

1 Answers1

7

The latter will generally first default-construct the vector, then reallocate the vector's storage to accommodate the new length (if larger than the default) (see here for assembly code). In contrast, there will be only one allocation for the first variant (less assembly code).

Note that compiler optimizations may well see through this, but there is another reason (other than avoiding premature pessimization) to prefer the first: By explicitly initializing all members in the constructor initialization list (or inline), you can have tooling that informs you when you leave something uninitialized by accident.

schorsch312
  • 5,553
  • 5
  • 28
  • 57
Max Langhof
  • 23,383
  • 5
  • 39
  • 72