0

In this example :

#include <iostream>
#include <vector>
#include <string>

typedef std::vector<std::string> vs;

vs test1()
{
  vs strings;
  strings.push_back("a");
  strings.push_back("b");
  strings.push_back("c");
  return strings;
}

void test2(vs& strings)
{
  strings.push_back("a");
  strings.push_back("b");
  strings.push_back("c");
}

int main()
{
  vs data = test1();
  test2(data);
  return 0;
}

I test two ways to fill a vector of string. I presume that in first case we copy the vector, in the second case it's probably better because we just give the ref of the vector. So what is the good way, the copy is it a very big cost for the computer ?

thanks for you answer !

Uyghur Lives Matter
  • 18,820
  • 42
  • 108
  • 144
jerome
  • 54
  • 5
  • 1
    Most modern compilers will generate code which probably equal in efficiency. Although note that you'll end up with 6 strings in `data` - is this what you were expecting? – Nick Oct 25 '13 at 14:52
  • 1
    Your functions do different things. If you wanted to guarantee that they do the same, you would have to check and/or clear the input in the first version, which would have some overhead. You would also have to document that. – juanchopanza Oct 25 '13 at 14:55
  • 1
    @godel9 unfortunately the chosen answer seems to suggest using the worse of the two options. – juanchopanza Oct 25 '13 at 14:58

2 Answers2

3

For clarity, I'd suggest the first. There should be no impact on performance due to NRVO.

If the purpose is to create a new object and return it, the first. If it's to modify an existing one, use the second.

They don't exactly do the same thing:

int main()
{
  vs data{"test"};
  data = test1();
  //data is {a, b, c}

  vs data2{"test"};
  test2(data2);
  //data is {test, a, b, c}
  return 0;
}
Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
2

The first one creates a new vector and there're just those three strings. The second, adds those three string at the end of an existing vector. So, the functionality is a bit different.

In case of performance, since there're (N)RVO and move semantics you can use first one which is more clear.

masoud
  • 55,379
  • 16
  • 141
  • 208