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.
source
share