If you are going to use a temporally variable use a const qualifier, so the compiler can add optimizations knowing that the value will not change:
string strLine;//not constant
int index = 0;
const int strLenght = strLine.Length();
while(index < strLine.length()){//strLine is not modified};
Chances are that the compiler itself make those optimizations when accessing the Length() method anyway.
Edit: my assembly is a little rusty, but i think that the evaluation takes place just once.
Given this code:
int main()
{
std::string strLine="hello world";
for (int i=0; i < strLine.length(); ++i)
{
std::cout << strLine[i] <<std::endl;
}
}
Generates this assembly:
for (int i=0; i < strLine.length(); ++i)
0040104A cmp dword ptr [esp+20h],esi
0040104E jbe main+86h (401086h)
But for this code
std::string strLine="hello world";
const int strLength = strLine.length();
for (int i=0; i < strLength ; ++i)
{
std::cout << strLine[i] <<std::endl;
}
generates this one:
for (int i=0; i < strLength ; ++i)
0040104F cmp edi,esi
00401051 jle main+87h (401087h)
The same assembly is generated if a const qualifier is not used, so in this case it doesn't make a difference.
Tried with VSC++ 2005