Please give me some codeadvice ?

hello,

Is match.pathKey.count() calculated once,
or will it be calculated every time the loop runs?

1
2
3
4
5
  for(int i =0;i<(match.pathKey.count());++i)
{
   //doSomething();
}


Is there a way to see what the compiler is really doing?
it is calculated once. Every time the loop is called. But not calculated on each interval of the loop.
The observable behaviour of the program would be "as-if" match.pathKey.count() is freshly evaluated before each iteration of the loop.
@JLBorges You might be right. I think it boils down to what he means by "calculated" I was speaking strictly of the local variable that is created when the loop is called.
what he means by "calculated"


I mean is this faster, or is is it exactly the same as the above?
1
2
3
4
5
6
int to =  match.pathKey.count();
for(int i =0;i<to;++i)
{
   //doSomething();
}
In general the second version would be faster, though it depends on the implementation of your function. If it's efficient enough, you might as well not even notice the difference.

As for the reason. In your first version you obviously call the function before each iteration to check whether the condition holds. That means you compute every instruction that is within that function before every iteration.
In the second version you run that function only once and save its value, so all that's left is to compare i to that value before each iteration.

Correct me if I'm wrong ...
Last edited on
A simpler, version is this:

1
2
3
4
for(int count = 0, end = object.length(); count < end; count++)
{
    // do things
}


I use this as my default way of doing it, for while some length code is fast, most are not as fast as just calling it once.
For unspecified "things" being done, one can't even know if:

1
2
3
4
5
int to = match.pathKey.count();
for ( int i=0; i<to; ++i )
{
    // doSomething();
}


and

1
2
3
4
for (int i=0; i<match.pathKey.count(); ++i )
{
    // doSomething();
}


are equivalent. Performance speculations for non-specific situations seems pointless. Where the latter behavior is equivalent to the former, the compiler is allowed to generate identical code for both.


skorefish wrote:
Is there a way to see what the compiler is really doing?

Generate and review an assembly listing. Make sure you're compiling with optimizations on.
Generate and review an assembly listing

2 Questions:

1: How can one make such a listing
2: How do I get this text in my quotes:
skorefish wrote:
> How can one make such a listing

GNU, LLVM -S
http://gcc.gnu.org/onlinedocs/gcc-4.9.2/gcc/Overall-Options.html#Overall-Options

Microsoft: /FA http://msdn.microsoft.com/en-us/library/367y26c6.aspx


2: How do I get this text in my quote

See 3.) Quotation Tags in http://www.cplusplus.com/articles/z13hAqkS/
Topic archived. No new replies allowed.