Are the days of passing const std::string & as a parameter over?

后端 未结 13 1943

I heard a recent talk by Herb Sutter who suggested that the reasons to pass std::vector and std::string by const & are largely gon

13条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 17:15

    This highly depends on the compiler's implementation.

    However, it also depends on what you use.

    Lets consider next functions :

    bool foo1( const std::string v )
    {
      return v.empty();
    }
    bool foo2( const std::string & v )
    {
      return v.empty();
    }
    

    These functions are implemented in a separate compilation unit in order to avoid inlining. Then :
    1. If you pass a literal to these two functions, you will not see much difference in performances. In both cases, a string object has to be created
    2. If you pass another std::string object, foo2 will outperform foo1, because foo1 will do a deep copy.

    On my PC, using g++ 4.6.1, I got these results :

    • variable by reference: 1000000000 iterations -> time elapsed: 2.25912 sec
    • variable by value: 1000000000 iterations -> time elapsed: 27.2259 sec
    • literal by reference: 100000000 iterations -> time elapsed: 9.10319 sec
    • literal by value: 100000000 iterations -> time elapsed: 8.62659 sec

提交回复
热议问题