Question 3 about optimization

Sep 26, 2022 at 1:25pm
which one is better:

 
for(int i=0;i<(int)strlen(bTitle);i++)

or
1
2
int titleLength = (int)strlen(bTitle);
for(int i=0;i<titleLength;i++)

I think the second one because It does not need to calculate bTitle everytime. Am I wrong here?
Sep 26, 2022 at 1:27pm
If
It does not need to calculate bTitle everytime
then the compiler could simply optimise any such calculation out.
Sep 26, 2022 at 2:01pm
The first one is better because it's easier to read. (others might disagree)

The second one is better because it avoids calling strlen (which loops through the whole string) multiple times.

Will the compiler be able to optimize the first one? Maybe, but I wouldn't count on it.
Sep 26, 2022 at 2:05pm
Thank you @Peter, that's what I needed)

You too @lastChance
Sep 26, 2022 at 2:47pm
Or perhaps even
 
for ( int i = 0 ; bTitle[i] != '\0' ; i++ )


If you're traversing the whole string anyway, you may as well stop when you find the \0 yourself.

Then you only need traverse it once.
Sep 26, 2022 at 2:55pm
it may also depend on what the loop body does (can you do it with a built in function? those loop behind your back, but its been tuned, hopefully). building off the last one, a pointer mimics a range based for loop, which can be handy.

for(char* cp{bTitle}, *cp; cp++)
... *cp = whatever;

Sep 26, 2022 at 2:56pm
Thanks @salem, that's what I use currently when I duel with c-string arrays, or more precisely for ( int i = 0 ; bTitle[i] ; i++ ), I was just curious about what I used to code before 2013.

Sep 26, 2022 at 4:14pm
If you change the size of a c-style string within the loop, then you'll need to re-evaluate the size in every loop if you use a size somewhere.

However, the way to work with c-style strings is via a pointer and test whether the deref pointer has a 0 value (end) or not (as others have stated above).

Note that some of the c string functions (eg strcat do an internal equivalent of strlen() ).
Topic archived. No new replies allowed.