|
|
Warp wrote:
> The std::vector reserves an entire array of objects, rather than
> reserving them one-by-one.
Ok, cool. I would have guessed std::vector would allocate an array of pointers.
> The temporary given as parameter is created only once, not 64 times.
So the declaration is essentially hoisted from out of the loop? Makes sense.
> What is done 64 times is calling the copy constructor of hgeSprite
OK. I know the assignment operator, and the constructor, but I never heard
of a copy constructor. <google> Oh, I see. It's a constructor with a
particular type for the argument. OK.
> a copy constructor should not be significantly slower than calling the
> regular constructor.
It doesn't look like it, but doesn't it have to "construct" the temporary,
then invoke the copy constructor? It's not like the compiler can construct
directly into the array element that std::vector allocated, can it? And
wouldn't it have to call the destructor on the temporary 64 times after it
was copied (assuming it has a destructor)?
It looks like the code you wrote initializes a temporary, then passes it (by
address, presumedly) to std::vector.push_back(), which then has to copy it
into an internal array. Then the code reinitializes the same temporary for
the next iteration (assuming the code is even a little smartly compiled). If
the sprite has a destructor, doesn't it need to call that before freeing the
temporary? How can the compiler know the ... Oh, is std::vector inlined
enough that the compiler can see it's getting inserted directly into a
particular array element? If so, that would make sense, yes.
> 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.
Hmmm... How does the temporary get constructed? Wouldn't it be 64 calls to
the constructor (taking the various individual arguments for the sprite) and
then 64 calls to copy that data to the one that's in std::vector?
> 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 I said, I'm never (well, rarely) against clarity and idiom in favor of
micro-performance optimizations. Especially when you're talking about
initialization which you presumably do only once.
--
Darren New, San Diego CA, USA (PST)
The NFL should go international. I'd pay to
see the Detroit Lions vs the Roman Catholics.
Post a reply to this message
|
|