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.
s
?It's all relative.
PHP is interpreted, but if s.length
drops into a compiled part of the PHP interpreter, it will not be slow. But even if it is slow, what about the time spent in s[i]
, and what about the time spent in cout <<
?
It's really easy to focus on loop overhead while getting swamped with other stuff.
Like if you wrote this in C++, and cout
were writing to the console, do you know what would dominate? cout
would, far and away, because that innocent-looking <<
operator invokes a huge pile of library code and system routines.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With