Why C++ lambda is slower than ordinary function when called multiple times?

后端 未结 1 1245
孤独总比滥情好
孤独总比滥情好 2020-12-14 00:58

I just have tried to compare performance of lambda expressions in C++11, so I did the test -- compute sum of elements in a vector of double values. Here is the

相关标签:
1条回答
  • 2020-12-14 01:28

    It turned out, that this is not any issue with lambda expressions, just the compiler optimized-out the outer loop in the first case by caching the result of the sum() function. After change the first case to this form:

    out = 0.0;
    for (size_t i = 0; i < MAX; ++i)
    {
        out += sum(v);
        v[i] = 1.0; // this adds O(1) time and prevents caching
    }
    

    both cases timings are approximately equal, with lambda as a favourite.

    0 讨论(0)
提交回复
热议问题