Code Efficiency C++

For larger programs, code efficiency starts to become a big deal. Does it matter if we say (size > 0) or (size > capacity) regarding capacity += size ?

1
2
3
4
5
6
7
8
9
10
    int_vec(int sz, int fill_value)
    : capacity(10), size(sz)
    {
        if (size < 0) cmpt::error("can't construct int_vec of negative size");
        if (size > 0) capacity += size;    // Can it be (size > capacity) ? 
        arr = new int[capacity];
        for(int i = 0; i < size; ++i) {
            arr[i] = fill_value;
        }
    }


I ran the code, and the output was the same, but I believe in terms of efficiency, (size > capacity) might be better, since it increments capacity when it is actually necessary. However, (size > 0) does it everytime, even if capacity is 10, and size is 1, then the capacity still gets increased.
Shouldn't there also be an exit if the first condition (if statement) is met ?
> Shouldn't there also be an exit if the first condition (if statement) is met ?

For size and capacity, consider using std::size_t instead of int.
http://en.cppreference.com/w/cpp/types/size_t

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <algorithm>
#include <memory>

struct int_vec
{
    explicit int_vec( std::size_t sz, int fill_value = 0 )
    {
        size = sz ;
        capacity = std::max( MIN_CAPACITY, size ) ;
        arr = new int[capacity] ;
        std::uninitialized_fill_n( arr, size, fill_value ) ;
    }

    // ...
    
    private:
    
        std::size_t size ;

        static constexpr std::size_t MIN_CAPACITY = 10 ;
        std::size_t capacity ;

        int* arr ;
};
To be honest in "larger programs" code efficiency is hardly ever the problem, it is far more likely to be an issue of a bad algorithm, bad data design or bad inter-process communication. Low level coding is more likely to be a concern in smaller programs (or specific hot-spots in a larger program) that are executed many times - within a loop for example or on a large data set.

Premature optimisation of code can do far more damage than good. And while knowing how minute details can impact performance is interesting, it is very, very rare that those kind of details have a significant effect in the real world.
Topic archived. No new replies allowed.