Steve smorrey at gmail.com
Wed Feb 7 16:43:58 MST 2007

```Well that actually made it go from 110,000 to 130,000 but...
We aren't comparing apples to apples either.
Your code is more correct since it actually flips the entire string
starting at position 0, whereas my code flips starting at position 1
(by flaw).

So I fixed my flaw in the only way that worked (the obvious fix of
starting y at -1 instead of 0 causes the code to not pass through the
function.

s[y-1] = ~s[y-1];

The results are precisely in between at 120,000

Which got me thinking that maybe a standard while loop is not the
proper solution here.  So I turned it on it's head with a do while
which gave me 100,000 which is a pretty good speed up!

do{
s[y] = ~s[y];
}while(y++ <= s.length());

Thanks for making me take a long hard look at my loops :D

Regards,

On 2/7/07, Nicholas Leippe <nick at leippe.com> wrote:
> On Wednesday 07 February 2007 16:13, Steve wrote:
> > Turns out I had to create an assignment to get it function as I wanted.
> >
> > s[y] = ~s[y];
>
> Yes, that would seem more correct.
>
> [snip]
>
> > inline void flip(std::string& s){
> >       int y = 0;
> >       while(y++ < s.length()){
> >               s[y] = ~s[y];
> >       }
> > }
>
> Try this optimization:
>
> inline void flip(std::string& s) {
>         int len = s.length(); // compute the string length only once
>         for (int y = 0; y < len; y++) {
>                 s[y] = ~s[y];
>         }
> }
>
>
> Depending on how std::string.length() is implemented, the compiler may already
> have been able to do this optimization for you.  You can test by comparing
> both sets of code with optimizations turned off.
>
>
> /*
> PLUG: http://plug.org, #utah on irc.freenode.net
> Unsubscribe: http://plug.org/mailman/options/plug
> Don't fear the penguin.
> */
>

```