How to help the compiler to optimize lambda calls?

Viewed 104

The use of lambdas can be a great boost to code readability, when allowing data structure traversal to be extracted to a separate function. Here is a minimal example:

static inline void forXY(int v, std::function<void(int,int)> body) noexcept {
  for(int y = 0 ; y<v ; y++) {
    for(int x = 0 ; x<v ; x++) {
      body(x, y);
    }
  }
}

static void job() noexcept {
  forXY(100, [](int x, int y) { printf("%d %d\n", y, x); });
}

However, even in this simple case where everything is under control (-O3, no other call site, no capture, no template, no external symbol, no exported symbol, no exception), the compiler (clang 12.0.5 in my case) is not optimizing the lambda call away.

Did I miss something obvious? Maybe there is something in my code that prevents the compiler from detecting that inlining the function will lead to the same behavior?

1 Answers

Do not use std::function, use templated argument for body so the compiler can actually see the lambda when compiling forXY. Otherwise it resorts to type erasure and virtual calls inside std::function. – yeputons

Using this idea, here is the improved code:

template <typename F>
static inline void forXY(int v, F body) noexcept {
  for(int y = 0 ; y<v ; y++) {
    for(int x = 0 ; x<v ; x++) {
      body(x, y);
    }
  }
}
Related