c++ - 虚拟函数调用的性能作为for循环中的上限

标签 c++ performance

我有一个定义函数 run 的类的以下示例,该函数依赖于对虚函数 get_vars 的调用(我正在考虑行 for (auto int_vars_it : get_vars()) ...).

我的问题是:我的示例的性能是否会因为我在 for 循环的上限调用 get_vars() 而变慢?我担心循环的每个实例都会调用该函数,如果循环运行多次,这可能会降低性能。

#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;
}

最佳答案

它只会被调用一次并返回对 std::vector 的引用。之后,它将迭代 vector 的内容,这些内容将在某个时候被翻译成经典的 for 循环。

关于c++ - 虚拟函数调用的性能作为for循环中的上限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45772806/

相关文章:

c++ - QLabel高亮搜索词

c++ - C 中的函数指针 - 地址运算符 "unnecessary"

c++ - Arduino 仅在代码的一部分延迟

java - Espresso : What are the advantages/disadvantages of having multiple tests vs. 一个用户旅程?

c - gprof profiler 说我的 C 程序花费的时间比实际少得多

c++ - OpenCV 3d点投影

c++ - 是否可以以每秒 60 次的速度从点数据构建热图?

performance - Mongodb 多重查询或数据库规范化

node.js - 在哪里存储一致的 JSON、Redis 或全局变量?

java - 如何提高 SWT 绘图性能?