F# に Matrix クラスがあり、(+) 演算子をオーバーロードするとします。次に、次のようになります。
type Matrix(n : int, m : int) =
...
static member (+) (A : Matrix, B : Matrix) =
let res = new Matrix(A.Dim1, A.Dim2) // suppose A and B have the same dimension
... // compute here the sum
res
C/C++ と比較すると、次のようになります。
static const Matrix operator+(const Matrix& A, const Matrix& B)
{
Matrix res(A.Dim1(), A.Dim2());
... // compute here the sum
return res;
}
ここで、スタック メモリに割り当てられる C++ バージョンとは対照的に、F# では行列res
がヒープ メモリに割り当てられることに注意してください。res
ここまでは順調ですね。両方のバージョンで合計演算の結果への「参照」が必要な場合に何が起こるかを観察します。
Matrix result = A + B; // deep copy in C++ (because res has to be destroyed after its return)
let result = A + B // shallow copy in F# (res was allocated in the heap memory)
ここで何かが欠けているのでしょうか、それとも F# の (+) 演算子は、浅いコピーと深いコピーの動作のために、C/C++ の対応する演算子よりも効率的になりますか?