[英]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()) ...
). 我有一个以下类的示例,该类定义了一个函数
run
,该函数run
依赖于对虚函数get_vars
的调用(我正在考虑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? 我的问题是:我的例子中的表现放慢,因为我使用的呼叫
get_vars()
中的上限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;
}
It will only get called once and return a reference to the std::vector
. 它只会被调用一次,并返回对
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. 之后,它将迭代向量的内容,并将其翻译为经典的
for
循环。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.