string strLine;//not constant int index = 0; while(index < strLine.length()){//strLine is not modified};
how many times is estimated strLine.length()
strLine.length()
whether to use nLengthwith nLengthassigned strLine.length()just before the loop
nLength
lengthwill be evaluated every time you go through the loop, however, since it lengthis a constant time ( O(1)), it does not matter much, and adding a variable to store this value is likely to have little effect with a small hit on reading the code (as well as breaking the code if the string is ever changed).
length
O(1)
length() , , , , , , , . , . , , , , .
, ... ( ). , :
string strLine; int stringLength = strLine.length(); int index = 0; while(index < stringLength);
, , , " ?"
, , , strLine , , . const. ( ), .
, , , . Hover-over , .
, " , ", . , length() - O (1), ( , ), - . , , , , .
, .
strLine.length() (i < strLine.length())
, , ( ).
, const, , , :
string strLine;//not constant int index = 0; const int strLenght = strLine.Length(); while(index < strLine.length()){//strLine is not modified};
, Length().
: , , . :
int main() { std::string strLine="hello world"; for (int i=0; i < strLine.length(); ++i) { std::cout << strLine[i] <<std::endl; } }
:
for (int i=0; i < strLine.length(); ++i) 0040104A cmp dword ptr [esp+20h],esi 0040104E jbe main+86h (401086h)
std::string strLine="hello world"; const int strLength = strLine.length(); for (int i=0; i < strLength ; ++i) { std::cout << strLine[i] <<std::endl; }
for (int i=0; i < strLength ; ++i) 0040104F cmp edi,esi 00401051 jle main+87h (401087h)
, , .
VS++ 2005
, string::length, , O (1), . volatile, , , , .
string::length
, , . . , , , , .
Since you are not changing the line, should you not use
const string strLine;
Simple, because then the compiler gets some additional information about what can and cannot change, but I'm not sure how smart the C ++ compiler can get.
strLine.length() will be evaluated every time you go around the loop.
You are right that it would be more efficient to use nLength, especially if it is strLinelong.
strLine