Why should I prefer to use member initialization lists?

后端 未结 9 1256
醉酒成梦
醉酒成梦 2020-11-21 04:43

I\'m partial to using member initialization lists with my constructors... but I\'ve long since forgotten the reasons behind this...

Do you use member initialization

9条回答
  •  难免孤独
    2020-11-21 05:23

    Just to add some additional info to demonstrate how much difference the member initialization list can mak. In the leetcode 303 Range Sum Query - Immutable, https://leetcode.com/problems/range-sum-query-immutable/, where you need to construct and initialize to zero a vector with certain size. Here is two different implementation and speed comparison.

    Without member initialization list, to get AC it cost me about 212 ms.

    class NumArray {
    public:
    vector preSum;
    NumArray(vector nums) {
        preSum = vector(nums.size()+1, 0);
        int ps = 0;
        for (int i = 0; i < nums.size(); i++)
        {
            ps += nums[i];
            preSum[i+1] = ps;
        }
    }
    
    int sumRange(int i, int j) {
        return preSum[j+1] - preSum[i];
    }
    };
    

    Now using member initialization list, the time to get AC is about 108 ms. With this simple example, it is quite obvious that, member initialization list is way more efficient. All the measurement is from the running time from LC.

    class NumArray {
    public:
    vector preSum;
    NumArray(vector nums) : preSum(nums.size()+1, 0) { 
        int ps = 0;
        for (int i = 0; i < nums.size(); i++)
        {
            ps += nums[i];
            preSum[i+1] = ps;
        }
    }
    
    int sumRange(int i, int j) {
        return preSum[j+1] - preSum[i];
    }
    };
    

提交回复
热议问题