mem_fn
is smaller and faster than bind
. Try the following program with your favorite compiler and compare:
- The size of the resulting executable and
- The number of seconds reported as being spent.
You can compare the performance of bind
versus mem_fn
by changing the 1 to a 0 in the #if
line.
#include <iostream>
#include <functional>
#include <chrono>
struct Foo
{
void bar() {}
};
int main(int argc, const char * argv[])
{
#if 1
auto bound = std::bind( &Foo::bar, std::placeholders::_1 );
#else
auto bound = std::mem_fn( &Foo::bar );
#endif
Foo foo;
auto start = std::chrono::high_resolution_clock::now();
for( size_t i = 0; i < 100000000; ++i )
{
bound( foo );
}
auto end = std::chrono::high_resolution_clock::now();
auto delta = std::chrono::duration_cast< std::chrono::duration< double >>( end - start );
std::cout << "seconds = " << delta.count() << std::endl;
return 0;
}
Results will vary, but on my current system the mem_fn
version of the executable is 220 bytes smaller and runs about twice as fast as the bind
version.
And as a bonus feature, mem_fn
doesn't require you to remember to add std::placeholders::_1
like bind does
(on pain of an obscure templated compiler error).
So, prefer mem_fn
when you can.