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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With