c++ - std::function 是否比自动存储 lambda 函数重

标签 c++ c++11 lambda auto std-function

我听说在处理 lambda 函数时,std::function 的成本比 auto 高。有效的现代 c++ item5。我想要的是通过一些示例代码阐明为什么 std::function 使用的内存比 auto 更多的机制。 有人可以帮助我吗?

编辑

class Widget {
public:
  Widget(int i) : i_(i) {}
  bool operator<(const Widget& o) { return o.value() > i_; }
  int value() const { return i_; };
private:
  int i_;
  int dummy_[1024];
};

int main() {
  // performance difference between auto and std::function
  { 
    auto less1 = [](const auto& p1, const auto& p2) {
      return *p1 < *p2;
    };
    std::cout << "size of less1: " << sizeof(less1) << endl;

    function<bool(const std::unique_ptr<Widget>&,
                  const std::unique_ptr<Widget>&)>
        less2 = [](const std::unique_ptr<Widget>& p1,
                   const std::unique_ptr<Widget>& p2) {
          return *p1 < *p2;
        };
    std::cout << "size of less2: " << sizeof(less2) << endl;

    {
      // auto
      std::vector<std::unique_ptr<Widget>> ws1;
      for (auto i = 0; i < 1024*100; ++i) {
        ws1.emplace_back(new Widget(std::rand()));
      }

      auto start = std::chrono::high_resolution_clock::now();
      std::sort(ws1.begin(), ws1.end(), less1);
      auto end = std::chrono::high_resolution_clock::now();
      cout << ws1[0].get()->value() << " time: " << (end - start).count() << endl;
    }

    {
      // std::function
      // 25% slower than using auto
      std::vector<std::unique_ptr<Widget>> ws2;
      for (auto i = 0; i < 1024*100; ++i) {
        ws2.emplace_back(new Widget(std::rand()));
      }

      auto start = std::chrono::high_resolution_clock::now();
      std::sort(ws2.begin(), ws2.end(), less2);
      auto end = std::chrono::high_resolution_clock::now();
      cout << ws2[0].get()->value() << " time: " << (end - start).count() << endl;
    }
  }
  return 0;
}

来自https://github.com/danielhongwoo/mec/blob/master/item5/item5.cpp

我认为这段代码告诉我使用 std::function 比使用 auto 慢。但不使用内存。我只想用一些真实的代码来证明这一点。

最佳答案

std::function 可以存储任意可调用对象。因此,In 必须进行类型删除 才能存储任意类型的内容。这在一般情况下可能需要动态分配,并且在每次调用 operator () 时肯定需要间接调用(虚拟调用或通过函数指针调用)。

lambda 表达式的类型不是 std::function,它是一个定义了operator() 的未命名类类型(lambda 的闭包类型)。使用 auto a 来存储 lambda 使 a 成为这种精确的闭包类型,没有开销。

关于c++ - std::function 是否比自动存储 lambda 函数重,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48007520/

相关文章:

c++ - 为什么 fill() 在一维数组上使用时编译,但在多维数组上不编译

C++ 访问函数参数私有(private)变量

c++ - 我能以某种方式不写出完整的限定返回类型名称吗?

c++ - 在函数方法中使用 std::thread

java - 为什么传递的数组不能使用lambda函数

c++ - 延迟函数模板实例化

C++ - 类模板成员的定义

c++ - 为什么没有 bool std::operator==(T1* a, std::shared_ptr<T2> b) 的重载?

amazon-web-services - API 网关是否引入了显着延迟?

c++ - 初始化列表中的 lambda 返回