Cycle counter and pointers

I write a small specialized C99 library for graphs, and I often get form loops:

for(int i = 0; i < graph->nvertices; ++i) {
  // ...
}

I am wondering if this is a good practice, especially in the case of a loop. At first I thought that the compiler would be smart enough to look at "graph-> nvertices" only once, instead of looking at it at each iteration, but this seems impossible, since graphs-> nvertices can change inside the loop. Is it smarter and faster to write:

const int N = graph->nvertices;
for(int i = 0; i < N; ++i) {
  // ...
}

This seems faster because it does not need to look at the pointer several times, but this requires the creation of a new variable.

Note. I think this is such a situation when it’s nice to read a little assembler code to see what the compiler actually does, if anyone has a good link, I am open to suggestions.

+3
source share
7 answers

Try using higher optimization parameters, some compilers should be able to optimize this for you. You can also iterate backwards only by initializing the counter with the expression:

for (int i = graph->nvertices; i >= 0; --i) 
  ..

However, you will be detrimental to cache performance. I think that the method you proposed is the most straightforward one that can be understood by the compiler and the next person reading your code.

+3
source

. , nvertices , , , ? .

, , .

+3

.

const int N = graph->nvertices;
int i = 0;
for(; i < N; ++i) {
  // ...
}
+1

, , . , .

, , , .

, , .

+1

. objdump :

objdump -d executable

, :

objdump -d executable | sed -n '/<main>/,/^$/p'
+1

, . .

, , , , .

0

. :

for(size_t i = 0, n = graph->nvertices; i < n; ++i) {
  // ...
}
0

All Articles