Reputation: 55
For Leetcode question 1312 ,I implemented a pass by value solution and my execution time for a testcase was above 120ms, for the same test case in a pass by reference the execution time drastically reduced to about 8ms , HOW? Here are both solutions:
120ms + solution / not accepted:
class Solution {
public:
vector< vector<int> > dp;
int insert(string s,int l,int r)
{
if(dp[l][r]!=-1)
return dp[l][r];
else if(l>=r)
return 0;
if(s[l]==s[r])
dp[l][r] = insert(s,l+1,r-1) ;
else
dp[l][r] = 1 + min( insert(s,l+1,r), insert(s,l,r-1) ) ;
return dp[l][r];
}
int minInsertions(string s) {
dp.resize(s.length()+1, vector<int> (s.length()+1,-1) );
return insert(s,0,s.length()-1);
}
};
~8ms solution :
class Solution {
public:
vector< vector<int> > dp;
int insert(string& s,int l,int r)
{
if(dp[l][r]!=-1)
return dp[l][r];
else if(l>=r)
return 0;
if(s[l]==s[r])
dp[l][r] = insert(s,l+1,r-1) ;
else
dp[l][r] = 1 + min( insert(s,l+1,r), insert(s,l,r-1) ) ;
return dp[l][r];
}
int minInsertions(string& s) {
dp.resize(s.length()+1, vector<int> (s.length()+1,-1) );
return insert(s,0,s.length()-1);
}
};
I have a couple of questions:
Thank You.
Upvotes: 1
Views: 207
Reputation: 238351
Is the execution time difference (between a function with pass by reference and pass by value) significant in C++?
It can be significant, and it can be insignificant. It depends.
I implemented a pass by value solution and my execution time for a testcase was above 120ms, for the same test case in a pass by reference the execution time drastically reduced to about 8ms
The result of this experiment demonstrates quite clearly a case where the time difference appears to be significant - although without information about variance of the measurements, we cannot be certain that the results are significant statistically.
Why is the difference so significant?
You can find out using a profiler. Given that the change of the argument to a reference appears to improve the speed significantly, it would be reasonable to guess that most of the time is spent on creating multiple copies of the argument.
Does it happen only for strings
It doesn't happen only for strings. You'll find that there are other types that are slow to copy as well.
I mean do primitive/built-in data-types behave in the same way?
Probably not.
How much time does it take to copy an integer? Integers are usually a 1-8 bytes. It takes a about single instruction.
How much time does it take to copy a string? How big even is a string? Even sizeof(std::string)
is more than the largest integer type on your system. Then there is the dynamic array, which may potentially be gigabytes in size. Copying a gigabyte takes more time than copying 8 bytes. Even if the string isn't that massive, its copy may involve dynamic allocation. Dynamic allocation is much slower than simply copying an integer.
Would pass by pointer result in the same execution as pass by reference?
You can find out by measuring. But I can tell you that yes.
Upvotes: 6