title: Best Performance for Getter & Setter
body: <p>Recently i did some performance tests using getter and setter methods. I'm still not sure which is the best method to use them in c++.
  (there is no difference using small types like int etc.)</p>
  
  <pre><code>string i;
  
  string GetTest()
  {
      return i;
  }
  void SetTest(string i)
  {
      this-&gt;i = i; //copy
  }
  </code></pre>
  
  <p>This would be the way, how I would use it in java/C#. No reference/pointer and very slow in c++. 
  For strings, vectors and other "big" types this is very slow and bad if it gets called frequently</p>
  
  <pre><code>string i;
  const string&amp; GetTest()
  {
      return i;
  }
  void SetTest(const string&amp; i)
  {
      this-&gt;i = i; //copy
  }
  </code></pre>
  
  <p>At the moment I'm using this version above, it's much faster than using no references for the parameter and return value and with const I make sure, it won't be changed.</p>
  
  <pre><code>string* i;
  
  string&amp; GetTest()
  {
      return *i;
  }
  void SetTest(string&amp; i)
  {
      this-&gt;i = &amp;i;
  }
  </code></pre>
  
  <p>This version, using a pointer is faster than just using references, but I think it's harder to read, and if you want to work with the value inside the class, you have to work with the pointer.</p>
  
  <p>Beside using references / pointers it might also improve the performance a little bit by inlining frequently called getter &amp; setters, since they are small functions.</p>
  
  <pre><code>inline GetTest(){....}
  inline SetTest(){....}
  </code></pre>
  
  <p>But as already mentioned, I'm still not sure which would be the best way in c++ to use them, or if there are other ways. It would be good to eliminate these ambiguities.</p>
  
  <p>Edit:</p>
  
  <p>Coming back to this after nearly 4 years,
  here is my advice I would give now for modern C++: (more helpful than any text)</p>
  
  <p><a href="https://www.youtube.com/watch?v=xnqTKD8uD64" rel="nofollow noreferrer">https://www.youtube.com/watch?v=xnqTKD8uD64</a> 51:00</p>
  
  <p>I recommend to watch the full video, Herb Sutter such an amazing talker, in general follow CppCon.</p>