C++、性能を向上させるには、値伝達(pass by value)にしましょう.

2790 ワード

通常、C++プログラムを書くことを勉強しているときに聞いたことがありますが、関数のパラメータとしてpass by const referenceを参照する必要があります.これでは、値伝達によるコピー問題がなく、パフォーマンスを向上させることができますが、Want Speed? Pass by Valueという文章のタイトルは、パフォーマンスを向上させたいということですか?じゃ、伝える価値があるでしょう.
この論文では,右値rvalueと戻り値最適化RVOについて述べ,原則を導いた.
関数のパラメータをコピーしないでください.コンパイラは、値を渡すことでコピーする必要があります.
これは、以前に述べた値伝達と参照伝達の取捨選択を覆すのではなく、私たちの関数にパラメータをコピーする必要がある場合は、参照を伝達しないで、関数内部でコピー構造を呼び出す方法です.コンパイラが最適化され、パフォーマンスが向上するように、値を直接渡す必要があります.
二つの文章の中で挙げた例を貼りましょう.
1.vectorをソートします.
次のコードは、表示されたコピーがコンパイラによって最適化されないため、パフォーマンスが悪い.
std::vector<std::string> 
sorted(std::vector<std::string> const& names) // names passed by reference
{
    std::vector<std::string> r(names);        // and explicitly copied
    std::sort(r);
    return r;
}

コンパイラはRVOで最適化できるので、コピーを避けることができます.また、コンパイラが最適化されていなくても、最悪は上のコードと同じで、行が1行少なく、よりはっきり見えます.
std::vector<std::string> 
sorted(std::vector<std::string> names)
{
    std::sort(names);
    return names;
}

2.代入演算子.(実はCopy-and-Swap-Idiom)
パフォーマンスが悪い:
T& T::operator=(T const& x) // x is a reference to the source
{ 
    T tmp(x);          // copy construction of tmp does the hard work
    swap(*this, tmp);  // trade our resources for tmp's
    return *this;      // our (old) resources get destroyed with tmp 
}

パフォーマンス:
T& operator=(T x)    // x is a copy of the source; hard work already done
{
    swap(*this, x);  // trade our resources for x's
    return *this;    // our (old) resources get destroyed with x
}