Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any difference between the different methods of clearing the contents of a string variable?

Tags:

c++

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

like image 862
James N Avatar asked Oct 11 '15 14:10

James N


1 Answers

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.

like image 156
Jerry Coffin Avatar answered Oct 16 '22 22:10

Jerry Coffin