Hello F# folks,
Suppose we have a Matrix class in F# and you overload the (+) operator. Then, we will have something like this:
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
Comparing to C/C++, we would have something like this:
static const Matrix operator+(const Matrix& A, const Matrix& B)
{
Matrix res(A.Dim1(), A.Dim2());
... // compute here the sum
return res;
}
Now, observe that in F#, the matrix res
is allocated in the heap memory, in contrast with the C++ version, that allocates res
in the stack memory.
So far so good. Observe what happens when we want a "reference" to the result of the sum operation in both versions:
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)
Am I missing something here or the (+) operator in F# ends up being more efficient than its counterpart in C/C++, because of the shallow and deep copy behavior?