Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ using precalculated limiters in for loops

Tags:

c++

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?
like image 444
qttdbtstladdctd2wow Avatar asked Mar 01 '10 17:03

qttdbtstladdctd2wow


1 Answers

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.

like image 104
Mike Dunlavey Avatar answered Sep 26 '22 17:09

Mike Dunlavey