I heard that the cost is std::function
heavier than auto
for working with the lambda function. efficient modern C ++ item5. I want to explain the mechanism why it std::function
uses more memory than auto
with some code example. Can someone help me?
change
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() {
{
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;
{
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::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;
}
from https://github.com/danielhongwoo/mec/blob/master/item5/item5.cpp
I think this code shows that usage is std::function
slower than using auto. But not memory usage. I just want to prove it with some real code.
source
share