Re: Vector et al default initialized
On Jul 18, 10:39 am, Pavel Minaev <int...@gmail.com> wrote:
On Jul 18, 8:37 am, JoshuaMaur...@gmail.com wrote:
Specifically, I like to view std::vector as a better (built in) array.
However, because of this interface (and the semantics implied by it,
and formally spelled out in the standard), vectors incur an
unnecessary performance cost during construction. (A similar situation
probably exist for destruction.)
[]
All STL containers initialize their elements, even valarray (which is
arguably even more performance-oriented than vector). It was deemed
that safety is of more importance here. Besides, you might find that
initialization penalties are rather insignificant for vectors of built-
in types - I've used vector<char> as general-purpose output buffers
many times (a typical case where initialization is not needed), and
not once it lead to a performance problem.
I was once working on a custom protocol proxy server and used
std::vector<char> as a buffer for reading messages from TCP sockets.
The TCP messages started with a 4-byte message length followed by the
message body. It would read the message length from the socket, resize
the vector to that length and read the rest of the message into the
vector. Profiling revealed that the server spent ~30% of its run-time
zeroing out the vector when resizing. Obviously, zeroing out the
buffer which was going to be read() into was unnecessary. The solution
was a custom pod_vector<> container, which did not do initialisation
and could only be used with POD types. This also allowed using
realloc() for resizing, thus making it even more efficient.
Max
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]