Re: + or += (was: why not use i++ instead of ++i in for()?)
From: Hendrik Schober (SpamTrap_at_gmx.de)
Date: 02/24/04
- Previous message: Bo Persson: "Re: + or += (was: why not use i++ instead of ++i in for()?)"
- In reply to: Bo Persson: "Re: + or += (was: why not use i++ instead of ++i in for()?)"
- Next in thread: tom_usenet: "Re: why not use i++ instead of ++i in for()?"
- Messages sorted by: [ date ] [ thread ]
Date: Tue, 24 Feb 2004 20:03:16 +0100
Bo Persson <bop@gmb.dk> wrote:
> [...]
>
> > > > > > s = a + b + c + d;
>
> [...]
>
> > > > > > s = a;
> > > > > > s += b;
> > > > > > s += c;
> > > > > > s += d;
>
> [...]
>
> > T operator+(const T& l, const T& r)
> > {
> > T tmp(l);
> > tmp += r; // invoking 'operator+=()' here
> > return tmp;
> > }
> >
> > This makes it obvious that, regarding
> > performance, 'operator+()' can never be
> > better than 'operator+=()', but it will
> > often be worse.
>
> If you are unlucky, this will allocate a buffer and copy l once, then
> reallocate the buffer and copy l again, before adding r.
And then it copies again, upon return,
possibly also re-allocating again.
> Another implementation looks like this:
>
> T operator+(const T& l, const T& r)
> {
> T tmp;
> tmp.reserve(l.size() + r.size());
>
> return tmp.append(l).append(r);
> }
>
> A maximum of one memory allocation. Copies each character exactly once.
Twice. You keep forgetting the return
value.
(As a side note, I once had to learn
that returning the expression might
confuse the optimizer so that it cannot
apply the RVO.)
> [...]
> > Still, this creates three temporaries,
> > where Mark's code creates none. And his
> > code will not trigger any allocations
> > either.
> > What is your point?
>
> My point is:
>
> Best case, three temporaries on stack, but no allocations.
Plus one assignment.
> Mark's best case, no temporaries, but s is updated 3 more times.
3 times plus one assignment, minus three
temporaries.
> Worst case, three temporaries allocated, s is reallocated on assignment.
> Four in total.
>
> Mark's worst case, s is reallocated on assignment, and for each append. Four
> in total.
Right, in worst case it is as bad as the
other. Otherwise it's better.
> s = a + b + c + d;
>
> Looks much better. :-)
Maybe. I use it whenever perfromance is
not an issue. Generally, this should be
most of the time. In my case, it is never
more than 50%. (I usually don't do GUIs.)
> Bo Persson
Schobi
-- SpamTrap@gmx.de is never read I'm Schobi at suespammers dot org "Sometimes compilers are so much more reasonable than people." Scott Meyers
- Previous message: Bo Persson: "Re: + or += (was: why not use i++ instead of ++i in for()?)"
- In reply to: Bo Persson: "Re: + or += (was: why not use i++ instead of ++i in for()?)"
- Next in thread: tom_usenet: "Re: why not use i++ instead of ++i in for()?"
- Messages sorted by: [ date ] [ thread ]
Relevant Pages
|