BillyJean
BillyJean

Reputation: 1587

Performance of virtual function call as upper limit in a for-loop

I have the following example of a class that defines a function run that depends on a call to a virtual function get_vars (I am thinking of the line for (auto int_vars_it : get_vars()) ...).

My question is: Does the performance of my example slow down because I am using a call to get_vars() in the upper limit of the for-loop? I am worried that the function is being called every single instance of the loop, which may downgrade performance if the loop is run many times.

#include <iostream>

class Bas
{
  protected:
    using vars_type = std::vector<std::string>;

  private:
    vars_type vars_Base;

  protected:
    virtual vars_type &get_vars()
    {
        return vars_Base;
    }

  public:
    void push_back(const std::string &str)
    {
        get_vars().push_back(str);
    }

    void run()
    {
        for (auto int_vars_it : get_vars())
        {
            std::cout << int_vars_it << " ";
        }
    }
};


int main()
{
    Bas b;
    b.push_back("aB");
    b.run();

    return 0;
}

Upvotes: 0

Views: 48

Answers (1)

Horia Coman
Horia Coman

Reputation: 8781

It will only get called once and return a reference to the std::vector. After that, it's going to iterate on the vector's contents, which will be translated, to a classical for loop at some point.

Upvotes: 1

Related Questions