Reputation: 227
I have searched around a bit and found many examples and discussions of cases where you would use std::bind
instead of a lambda, but the burning question I have is whether or not there is any performance benefit to one over the other. I will describe my use case:
I have a generic A*
I have implemented, to which I pass successor, heuristic distance, and move cost functions.
Here is an example of my heuristic function ready to be passed off for a search (in both forms):
std::function<float(const Location*, const Location*)> hdist = std::bind(&TerrainMap::straightLineDist, this, std::placeholders::_1, std::placeholders::_2);
std::function<float(const Location*, const Location*)> hdist2 = [this](const Location* a, const Location* b){
return straightLineDist(a,b);
};
Is there any difference in the performance of these approaches? I realize the difference is probably negligible but I am curious enough to want to know.
Upvotes: 3
Views: 3312
Reputation: 131626
Is there any difference in the performance of these approaches?
Perhaps, perhaps not; as commenters suggest - profile to check, or look at the assemby code you get (e.g. using the GodBolt Compiler Explorer). But you're asking the wrong question, for two main reasons:
bind()
results, around in the part of your code that's performance-critical. std::function
variables in performance-critical areas of your code (except if this can be de-virtualized and inlined by the compiler).and one mind reason:
std::bind()
's) are usable, and useful, without being wrapped in std::function; this wrapper has its own performance penalty, so you would only be comparing one way of using these constructs.Bottom line recommendation: Just use Lambdas. They're cleaner, easier to understand, cheaper to compile, and more flexible syntactically. So don't worry and be happy :-) . And in performance-critical code, either use Lambda's without std::function
, or don't use any of the two.
Upvotes: 2