2

How to pass the std::string to the function to gain in speed of execution for this code snippet (strictly C++14, function only prints or logs received string):

#include <iostream>

void myFunction1(std::string msg)// this is faster ?
{
    std::cout << msg;
}

void myFunction2(const std::string& msg)// to this one is fastest?
{
    std::cout << msg;
}

int main()
{
    myFunction("Hello World");
    myFunction("Long string of 127 characters");
    myFunction("Another long string of 256 characters");
    return 0;
}
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
Artem
  • 79
  • 9
  • https://stackoverflow.com/questions/9394674/when-is-sizeofmypod-too-big-for-pass-by-value-on-x64 – 康桓瑋 Dec 29 '22 at 11:18
  • 1
    Please don't remove the `c++` tag. If you want answers to be limited to a certain version, add `c++??` in addition to `c++`, and additionally mention it in the question body. – HolyBlackCat Dec 29 '22 at 12:57
  • 1
    Passing by reference instead of by value is **always** faster than passing by value for any type larger than a pointer. – Michaël Roy Dec 30 '22 at 03:33
  • @MichaëlRoy, strictly speaking that is not always true. – Dmitry Kuzminov Jan 19 '23 at 00:37
  • In your example you don't provide `std::string` as an argument, but a string literal that is converted to a temporary `std::string`. If that is the main usage of your function, the answer to your question is not trivial and may become surprising. And I vote for reopening the question. – Dmitry Kuzminov Jan 19 '23 at 00:42
  • 1
    @DmitryKuzminov OK strictly speaking it's never slower. – Michaël Roy Jan 19 '23 at 01:36
  • 1
    @MichaëlRoy, even that is not true at least if you count not only passing but also usage. For example, it is better to pass `std::string_view` by value rather than by const reference, even though it is of size of 2 pointers. Dereferencing the reference may be more expensive than using values with known offsets. – Dmitry Kuzminov Jan 19 '23 at 02:49

1 Answers1

1

It depends. In this case you could (and should) pass std::string_view (which was added in C++17) to avoid a possible heap allocation when passing a large string literal.

But if you needed a null-terminated string, then std::string_view wouldn't work, and you'd have to pass either const std::string & or a custom string_view replacement that's always null-terminated.

Or, if you wanted to copy the string somewhere, you'd instead pass std::string by value and then std::move it.

HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207