对于Leetcode问题1312,我实现了按值传递解决方案,并且我对一个测试用例的执行时间在120ms以上,对于在通过引用传递的同一个测试用例中,执行时间急剧减少到大约8ms,怎么办?
这是两个解决方案:
120ms +解决方案/不接受:
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解决方案:
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);
}
};
我有一些问题:
谢谢。
最佳答案
Is the execution time difference (between a function with pass by reference and pass by value) significant in C++?
它可以是重要的,也可以是无关紧要的。这取决于。
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
该实验的结果非常清楚地证明了时差似乎很明显的情况-尽管没有有关测量方差的信息,但我们不能确定结果在统计学上是否显着。
Why is the difference so significant?
您可以使用探查器进行查找。鉴于将参数更改为引用似乎可以显着提高速度,因此可以合理地猜测,大部分时间都花在创建参数的多个副本上。
Does it happen only for strings
它不仅发生在字符串上。您会发现还有其他类型的副本也很慢。
I mean do primitive/built-in data-types behave in the same way?
可能不会。
复制整数需要多少时间?整数通常为1-8字节。它大约需要一条指令。
复制字符串需要多少时间?一串甚至有多大?甚至
sizeof(std::string)
都超过了系统上最大的整数类型。然后是动态阵列,其大小可能为千兆字节。与复制8个字节相比,复制1 GB所需的时间更多。即使字符串不是那么大,它的副本也可能涉及动态分配。动态分配比简单地复制整数要慢得多。Would pass by pointer result in the same execution as pass by reference?
您可以通过测量来找出。但是我可以告诉你,是的。
关于c++ - 在C++中,执行时间差异(带有按引用传递的函数和按值传递的函数之间)是否显着?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61112640/