Christopher Benson-Manica said:
Yesterday I changed some code to use std::vectors and std::strings
instead of character arrays. My boss asked me today why I did it, and
I said that the code looks cleaner this way. He countered by saying
that he was regarded the dyanamic allocation that C++ STL classes
perform as being very inefficient. He also said that he wasn't
particularly interested in clean code (!). My question to the group:
In what situations, if any, would you use fast but hackish C-style
code in favor of the convenient STL classes? Would your answer change
if you were forced to use a questionable implementation (such as,
not-so-hypothetically, Borland 4)?
By char arrays, do you mean
char array[200];
array = new char[200]; delete[] array;
array = static_cast<char*>(malloc(200u)); free(array);
array = :
perator new(200u); :
perator delete(array);
As regards memory allocation, the first way may be slightly faster, but not
always. The 2nd, 3rd, and 4th ways are usually the same. The default STL
allocators use the 4th way.
Which way is faster depends very much on the details of your scenario, such
as the size of the array, number of objects created, etc. If you create
lots of small arrays, then the 1st way may be faster.
In general, the STL containers are extremely fast, and might be faster than
your home-grown containers due to specializations, fancy algorithms, etc.
The STL allocators let you use pool allocators, but you can also that by
overloading Class
perator new. In the first case, the pool may be per
container; and in the second, the pool is shared across containers.
The STL containers also destruct their data by calling allocator.destroy on
each element, though in a good compiler this would be optimized away when
the element is a POD, as the statement has no effect.
The STL containers also default initialize their members, if you provide a
size parameter (but don't confuse this with reserve).
But std::string implementations may also provide an optimization for small
strings, namely to contain an element like char[32]. I don't know much
about this topic though, or whether any real implementations actually do
this.
As regards the topic of clean code versus hackish code, my theory is that
hackish code is easier to write and therefore produces immediate business
value (ie. profits). But it is harder to maintain and so over the long term
is more costly. How businesses fare with either method is an interesting
topic, and I have not done any formal research into the subject.
But also be aware that usage of STL does not automatically mean your code is
cleaner.