[LLVMdev] Deduplication of memory allocation

Daniel Berlin dberlin at dberlin.org
Fri May 1 08:48:53 PDT 2015


On Fri, May 1, 2015 at 8:34 AM, François Fayard
<fayard.francois at icloud.com> wrote:
> Hi,
>
> Even though this question does not only concern LLVM, it seems that only
> compilers guru can answer it. So I am giving a try here, hoping for the
> best.
>
> In a recent talk by Chandler Carruth, “Performance with algorithms,
> efficiency with data structures” (
> https://www.youtube.com/watch?v=fHNmRkzxHWs ), Chandler says that one should
> never return by reference for efficiency. Although I totally agree with him
> in most cases because pointers make it difficult for a compiler to optimise,
> I still don’t always have an efficient solution with value semantics. Here
> is the case that I am thinking of :
>
> ====
> std::vector<double> f(std::size_t i);
>
> auto v = std::vector<double>( n );
> for (std::size_t i = 0; i < 1000; ++i) {
>     auto w = f(i);
>     for (std::size_t k = 0; k < v.size(); ++k) {
>         v[k] += w[k];
>     }
> }
> ====
>
> which would be way slower than
>
> ====
> void f(std::size_t i, std::vector<double>& w);
>
> auto v = std::vector<double>( n );
> auto w = std::vector<double>( n );
> for (std::size_t i = 0; i < 1000; ++i) {
>     f(i, w);
>     for (std::size_t k = 0; k < v.size(); ++k) {
>         v[k] += w[k];
>     }
> }

Why?

Look up "Return value optimization".
:)




More information about the llvm-dev mailing list