9

Given a string variable set to some value:

string s = "Hello";

Is there any difference (performance, gotchas) between the following methods to clear the contents?:

s = ""

s = std::string()

s.clear()

I got the sample code from this answer to a question about clearing a variable https://stackoverflow.com/a/11617595/1228532

Community
  • 1
  • 1
James N
  • 603
  • 3
  • 8
  • 18
  • 1
    although the code behind may be different for the 3, I see no performance deifference ot special gotchas between them. – David Haim Oct 11 '15 at 14:11
  • 1
    It depends on whether you want to hold on to the allocated memory or discard that, too. – Kerrek SB Oct 11 '15 at 14:15
  • I _think_ the rule should be that if a class provides a sensible defined clear/truncate/etc method, that should be preferred to anything that involves assignment/temporaries/copyctors or such. – underscore_d Oct 11 '15 at 15:22
  • That's a good point, I'll keep that in mind – James N Oct 11 '15 at 15:41

1 Answers1

9

There are some noticeable differences.

clear sets the length of the string to 0, but does not change its capacity.

s="" or s = std::string() creates a whole new (empty) string, assigns its value to the existing string, and throws away the contents of the existing string. Especially if you're using an implementation of std::string that doesn't include the short string optimization, this may well be much slower than clear. To add insult to injury, it also means that if you add more data to the string, it'll end up reallocating the buffer starting from a tiny buffer that it will probably have to reallocate as the string grows.

Bottom line: clear will often be faster, not to mention giving a...clear expression of your real intent.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111