views:

117

answers:

3

I have a piece of performance critical code written with pointers and dynamic memory. I would like to rewrite it with STL containers, but I'm a bit concerned with performance. Is there a way to increase the size of a container without initializing the data?

For example, instead of doing

ptr = new BYTE[x];

I want to do something like

vec.insert(vec.begin(), x, 0);

However this initializes every byte to 0. Isn't there a way to just make the vector grow? I know about reserve() but it just allocates memory, it doesn't change the size of the vector, and doesn't allows me to access it until I have inserted valid data.

Thank you everyone.

+2  A: 

resize()

It may or may not do anything different than your insert(). Values are default constructed.

Noah Roberts
Urghh, thank you. Didn't saw it. Anyway, if values are default constructed, I won't bet on its performance.
Jaime Pardos
@Jamie: If this is the answer to your question, please upvote it by clicking the up arrow, and accept it by clicking the big check mark to the left of Noah's post.
John Dibling
I've got a 100% accept rate
Jaime Pardos
@Jaime, good boy.
Johannes Schaub - litb
+4  A: 

vector.resize(...) may be of help? You can specify the size that you want to resize to (going larger or smaller) and also intialize what you want the new elements to be initialized to.

Robb
+1  A: 

vec.resize( newsize ) is defined to have the same effect as

vec.insert( vec.end(), newsize - vec.size(), T() )

if newsize > vec.size()… but the compiler may have difficulty determining that it is growing, not shrinking, and by how much. You might try profiling with both.

If you're sure that the default initialization is taking time, explicitly eliminate it with your own constructor. (Even if the implicit constructor is fine, it's good to show intent.)

struct BYTE {
    char v;
    BYTE() {} // no default initialization!
    BYTE( char x ) : v(x) {}
    operator char&() { return v; }
    operator char const&() const { return v; }
    char *operator&() { return &v; } // not sure about operator&...
    char const *operator&() const { return &v; } // probably good in this case
};
Potatoswatter
Thank you. At last I've solved this using auto_ptr's.
Jaime Pardos