I thought that pass by reference should be faster then pass by value because the computer isn't copying data, it just points to the address of data.
But, consider the following C++ code:
#include <iostream>
#include <cassert>
#include <cmath>
using namespace std;
// do not use pass by reference& with this function, it will become so slow
unsigned long long computePascal(const unsigned int row, const unsigned int position) {
if (position == 1 || position == row)
return 1L;
unsigned long long left = computePascal(row-1, position-1);
unsigned long long right = computePascal(row-1, position);
unsigned long long sum = left + right;
return sum;
}
int main() {
int row, position;
cout << "Input row and position: ";
cin >> row >> position;
assert(position > 0 && position <= row);
unsigned long long pascalNumber = computePascal(row, position);
cout << pascalNumber << endl;
return 0;
}
Now this code is just a normal program that compute pascal number recursively by entering the desired row and position of the triangle.
I tried putting row 50 and position 7 and it computes around 1 second (pass by value). The output is about 13 million which is correct. So I thought that it could be faster if I pass by reference instead because it doesn't need to copy a lot of data. But this is very wrong and I don't know why it took longer time about 3 times the amount it took for passing by value.
The question is ...
Why this program computes so slow after I try changing it to pass by const reference?
Does it matter that because recursive function is an exception that you should pass by value rather than const reference?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…