POV-Ray : Newsgroups : povray.off-topic : New NearInfinity demo up : Re: New NearInfinity demo up Server Time
6 Sep 2024 21:20:22 EDT (-0400)
  Re: New NearInfinity demo up  
From: Warp
Date: 16 Dec 2008 12:20:04
Message: <4947e344@news.povray.org>
Darren New <dne### [at] sanrrcom> wrote:
> Warp wrote:
> > std::vector<hgeSprite> tile;
> > 
> > tile.reserve(8*8);
> > for(...)
> >   for(...)
> >     tile.push_back(hgeSprite(...));

> Not that I'd recommend micro-optimization over readability, but isn't this 
> going to be more inefficient than the other way? Doesn't this allocate a 
> sprite on the stack, pass it to tile.push_back(), which then has to copy it 
> to dynamically allocated memory anyway?

  The std::vector reserves an entire array of objects, rather than
reserving them one-by-one. (What the reserve() function does is that it
allocates space for that many objects, without actually instantiating them.)
So rather than having 64 allocations with 'new', there's only one.

  The temporary given as parameter is created only once, not 64 times.

  What is done 64 times is calling the copy constructor of hgeSprite
(for each element added to the vector). It of course depends on how
the copy constructor in question is implemented, but usually calling
a copy constructor should not be significantly slower than calling the
regular constructor.

  If we compare the amount of operations in both situations, they would be:

- 1 'new' call, vs. 64 'new' calls.
- 1 temporary instantiated, vs. none.
- 64 copy constructor calls, vs. 64 regular constructor calls.
- 1 temporary destruction, vs. none.

  Doing only 1 'new' rather than 64 might in itself make the whole thing
faster, even though there's an additional temporary creation/destruction.

  Anyways, even if there is some speed penalty, it's probably negligible.
As a reward your objects will be managed by std::vector, rather than you
having to manage them manually.

  (As an additional reward, the std::vector will require less memory than
the 64 individually allocated objects. Of course with 64 objects this is
nothing, but it might become significant with a larger number.)

-- 
                                                          - Warp


Post a reply to this message

Copyright 2003-2023 Persistence of Vision Raytracer Pty. Ltd.