c++ - 在C++中,执行时间差异(带有按引用传递的函数和按值传递的函数之间)是否显着?

标签 c++ c++14 c++17 pass-by-reference pass-by-pointer

对于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/

    相关文章:

    c++ - 可以使用对 shared_ptr 拥有的对象的引用吗?

    c++ - 是否需要在运算符(operator)身上丢弃垃圾?

    c++ - 使用来自 std::vector 的参数调用可变参数模板化函数

    c++ - 关于 [temp.variadic] 中包扩展的实例化的措辞

    c++ - makefile 自动删除 .o 文件

    c++ - 删除时堆损坏[]

    c++ - 无法推断模板参数 'N'

    c++ - 在改变其大小的循环中更新 boost multi_array 变量

    c++ - 如何对数组使用 unique_ptr

    c++ - 需要一种更快的方法在 C++ 中创建邻接列表