Estimation of a condition in a cycle?

string strLine;//not constant
int index = 0;
while(index < strLine.length()){//strLine is not modified};

how many times is estimated strLine.length()

whether to use nLengthwith nLengthassigned strLine.length()just before the loop

+3
source share
9 answers

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).

+4
source

length() , , , , , , , . , . , , , , .

+3

, ... ( ). , :

string strLine;
int stringLength = strLine.length();
int index = 0;
while(index < stringLength);
+2

, , , " ?"

, , , strLine , , . const. ( ), .

, , , . Hover-over , .

, " , ", . , length() - O (1), ( , ), - . , , , , .

, .

+2

strLine.length() (i < strLine.length())

, , ( ).

+1

, 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

+1

, string::length, , O (1), . volatile, , , , .

, , . . , , , , .

+1
source

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.

0
source

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.

-1
source

All Articles