Someone want to explain me which code is faster ? and what is the best way to optimise a string assignment ?
code 1 :
std::string result;
int main()
{
for(int i=0;i<1000;i++)
{
/*some code*/
result = stringVar;
/* some code using result */
}
}
code 2 :
int main()
{
for(int i=0;i<1000;i++)
{
/*some code*/
std::string result = stringVar;
/* some code using result */
}
}
And to assigne value :
std::string var;
var.assign("value");
//or
var="value";
And it’s possible to release memory used by the value before to add a new one ?
Thank if you can help me to understand that 🙂
In the case of:
the compiler must construct and destruct result each time through the for loop, probably requiring heap allocation and deallocation calls.
In the case of:
the string implementation might be able to optimize some heap allocation and deallocation away by only reallocation when blah is to big to fit in result’s current buffer.
var=x and var.assign(x) should result in the same code; I would not expect a substantial difference either way.