std::function overhead
suggest changestd::function uses type erasure and owns a copy or moved instance of its
callable. A callable that does not fit in the implementation's internal buffer
may require a dynamic allocation.
Implementations commonly use a small-object optimization for compact callables. The exact size and eligibility rules are implementation details, so code should not assume that an arbitrary lambda is allocation-free.
Consider this interface:
using MyPredicate = std::function<bool(const MyValue&, const MyValue&)>;
void sortMyContainer(MyContainer& container, const MyPredicate& predicate)
{
std::sort(container.begin(), container.end(), predicate);
}
The function uses the predicate only during the call and does not need to own it. A function template avoids type erasure and gives the optimizer a better chance to inline the call:
template<class Predicate>
void sortMyContainer(MyContainer& container, Predicate predicate)
{
std::sort(container.begin(), container.end(), std::move(predicate));
}
When a stable non-template interface is required, std::function may still be a
reasonable tradeoff. Calling through it usually requires an indirect call and
can inhibit inlining, but the practical cost depends on the implementation and
the surrounding work. Measure before optimizing it away.
Before C++26, the standard library has no general-purpose non-owning callable
wrapper. The C++26 working draft adds std::function_ref; projects using earlier standards can use
a project-specific equivalent when the callable's lifetime is well defined.
Current std::function also does not expose allocator control.