I'm not sure if the following code can cause redundant calculations, or is it compiler-specific?
for (int i = 0; i < strlen(ss); ++i)
{
// blabla
}
Will strlen()
be calculated every time when i
increases?
I'm not sure if the following code can cause redundant calculations, or is it compiler-specific?
for (int i = 0; i < strlen(ss); ++i)
{
// blabla
}
Will strlen()
be calculated every time when i
increases?
YES, in simple words. And there is small no in rare condition in which compiler is wishing to, as an optimization step if it finds that there is no changes made in
ss
at all. But in safe condition you should think it as YES. There are some situation like inmultithreaded
and event driven program, it may get buggy if you consider it a NO. Play safe as it is not going to improve the program complexity too much.If
ss
is of typeconst char *
and you're not casting away theconst
ness within the loop the compiler might only callstrlen
once, if optimizations are turned on. But this is certainly not behavior that can be counted upon.You should save the
strlen
result in a variable and use this variable in the loop. If you don't want to create an additional variable, depending on what you're doing, you may be ale to get away with reversing the loop to iterate backwards.Elaborating on Prætorian's answer I recommend the following:
auto
because you don't want to care about which type strlen returns. A C++11 compiler (e.g.gcc -std=c++0x
, not completely C++11 but auto types work) will do that for you.i = strlen(s)
becuase you want to compare to0
(see below)i > 0
because comparison to 0 is (slightly) faster that comparison to any other number.disadvantage is that you have to use
i-1
in order to access the string characters.Arrgh, it will, even under ideal circumstances, dammit!
As of today (January 2018), and gcc 7.3 and clang 5.0, if you compile:
So, we have:
ss
is a constant pointer.ss
is marked__restrict__
ss
(well, unless it violates the__restrict__
).and still, both compilers execute
strlen()
every single iteration of that loop. Amazing.This also means the allusions/wishful thinking of @Praetorian and @JaredPar doesn't pan out.
Yes, the
strlen()
function is called every time the loop is evaluated.If you want to improve the efficiency then always remember to save everything in local variables... It will take time but it's very useful ..
You can use code like below:
Yes,
strlen()
will be evaluated on each iteration. It's possible that, under ideal circumstances, the optimiser might be able to deduce that the value won't change, but I personally wouldn't rely on that.I'd do something like
or possibly
as long as the string isn't going to change length during the iteration. If it might, then you'll need to either call
strlen()
each time, or handle it through more complicated logic.