A clever compiler will do the second for you. So don't worry about this and don't be a victim of premature optimization!
You want the second one, because the length has a fixed value and you will avoid the call of the function per loop.
But will the compiler be clever enough to do so? Only if you tell him too! See the examples below:
First, I am compiling without optimization flags:
C02QT2UBFVH6-lm:~ gsamaras$ gcc -Wall nostore.c
C02QT2UBFVH6-lm:~ gsamaras$ ./a.out
That took 27.701602000 seconds wall clock time.
C02QT2UBFVH6-lm:~ gsamaras$ gcc -Wall store.c
C02QT2UBFVH6-lm:~ gsamaras$ ./a.out
That took 12.100676000 seconds wall clock time.
but what happens if we use an optimization flag?
C02QT2UBFVH6-lm:~ gsamaras$ gcc -O3 -Wall nostore.c
C02QT2UBFVH6-lm:~ gsamaras$ ./a.out
That took 0.004949000 seconds wall clock time.
C02QT2UBFVH6-lm:~ gsamaras$ gcc -O3 -Wall store.c
C02QT2UBFVH6-lm:~ gsamaras$ ./a.out
That took 0.005283000 seconds wall clock time.
Compiler did it better than me! Compilers are not that dumb nowadays, as some people mistakenly think.
For timing I used the Nomimal Animal's approach from my Time measurements.
Here is the cod I executed:
char* str = "What's faster? What's a premature optimization? Am I a vi$
int i = INT_MAX;
// int n = strlen(str);
// while(n);
while(strlen(str)) {
// do some random work so that you don't get 0 timing
int a = 3;
double pi = 3.14;
a /= pi;
a = a % (i + 1);
// break when 'i' is 0
if(!i)
break;
--i;
}
But are optimization flags that important in benchmarking? YES, check this question: Poor performance of stl list on vs2015 while deleting nodes which contain iterator to self's position in list