I do not know about php , but I can say what c++ does. Consider:
std::string s("Rajendra"); for (unsigned int i = 0; i < s.length(); i++) { std::cout << s[i] << std::endl; }
If you are looking for the definition of length() (right-click on length() and select "Go to definition") OR, if you are using Visual Assist X, then place the cursor on length() and press Alt+G , you will find the following:
size_type __CLR_OR_THIS_CALL length() const { // return length of sequence return (_Mysize); }
Where _Mysize is of type int , which clearly shows that the length of the string is precomputed and only the stored value is returned to each call to length() .
However, IMPO (in my personal opinion), this coding style is bad and should be avoided. I would prefer the following:
std::string s("Rajendra"); int len = s.length(); for (unsigned int i = 0; i < len; i++) { std::cout << s[i] << std::endl; }
Thus, you will save overhead when calling the function length() equal to the length of the string number of times, which saves clicking and popping up the stack frame. It can be very expensive when your string is large.
Hope this helps.
Rajendra uppal
source share