Search code examples
c++lambdac++11visual-c++-2010

Performance compare (normal function call vs for_each+mem_fun vs lambda expression) in C++


Which is the best one (in performance) among these snippets?

1)

for(list<Enemy*>::iterator iter = enemies.begin(); iter != enemies.end(); iter ++)
   (*iter)->prepare(time_elapsed);

2)

for_each(enemies.begin(), enemies.end(), [time_elapsed] (Enemy *e) {e->prepare(time_elapsed);});

3)

for_each(enemies.begin(), enemies.end(), bind2nd(mem_fun1<void, Enemy, GLfloat>(&Enemy::prepare), time_elapsed));

Solution

  • Lambdas are the fastest solution. There are special optimizations involved with taking references to stack-based variables. In addition, in C++0x, they're FAR more flexible than any of that bind stuff, and the first loop also has the clarity disadvantage. Lambdas are the winrar in every way.

    However, I'm seriously thinking micro-optimization, unless this is in a really, really inner loop that runs billions of times.