Passing by reference is usually better than passing by value in terms of performance (excluding built-in data types). So yes func(string&)
better than func(string)
. Provided that the passed string
can be changed when the function completes. If you are not going to change string
, use func(const string&)
.
On the other hand, I remember reading somewhere that string
optimized in STL. If you pass string
by value, this may not necessarily create a new string on the heap. Thus, transitioning by value may not be as expensive as you would expect. eg.
string s1 = "hello"; // new buffer allocated on heap and copied "hello" string s2 = s1; // s2 and s1 both 'may' refer to same heap ... s1 += " world"; // s2 continue referring to old heap ... // new heap created to accomodate "hello world" referred by s1
source share