In scripting languages like PHP having a for loop like this would be a very bad idea:
string s("ABCDEFG");
int i;
for( i = 0; i < s.length(); i ++ )
{
cout << s[ i ];
}
This is an example, i’m not building a program like this. (For the guys that feel like they have to tell me why this piece of code <insert bad thing about it here>)
If this C++ example was translated to a similar PHP script the lenght of the string would be calculated every loop cycle. That would cause an enormous perfomance loss in realistic scripts.
I thought the same would apply to C++ programs but when I take a look at tutorials, several open-source libraries and other pieces of code I see that the limiter for the loop isn’t precalculated.
- Should I precalculate the lenght of the string
s? - Why isn’t the limiter always precalculated? (seen this in tutorials and examples)
- Is there some sort of optimization done by the compiler?
It’s all relative.
PHP is interpreted, but if
s.lengthdrops into a compiled part of the PHP interpreter, it will not be slow. But even if it is slow, what about the time spent ins[i], and what about the time spent incout <<?It’s really easy to focus on loop overhead while getting swamped with other stuff.
Like if you wrote this in C++, and
coutwere writing to the console, do you know what would dominate?coutwould, far and away, because that innocent-looking<<operator invokes a huge pile of library code and system routines.