c++ - vector reseve then assign can improve performance -
if have assign char array vector ,is practice first reserve vector size assign array it?
will improve performance?
beacuse compiler no need allocate several time internaly should improve performance , not sure . assign taking in consideration before assigning?
doese assign (reserve) allocate size first , insert/copy?
note:-with assign mean assign function in vector (std::vector::assign)
example:-
void test_func(char* bigarray) { std::vector<char> v_data; int len=strlen(bigarray); v_data.reserve(len); v_data.assign(bigarray,bigarray+len); }
i'm not sure why question got downvoted seems valid ask this, rather going away , inventing kind of way benchmark vector may or may not give erroneous results.
anyway... if you've got decent sized array you're going assign vector, faster reserve() before assigning. however, there several caveats mean might not case. in fact, implementation dependent.
your vector have pre-defined size when created, when assign() performed, it's going start copying array elements vector. when vector reaches capacity, it'll allocation of (i think 1.5x or maybe 2x allocation strategy) , copy elements 1 vector another. however, allocation may extend memory (depending on whether operating system allow it) , copy operation may not take place. you'll not able predict this, not under control.
if input array of known size, better reserve() space need ahead of time avoid these possible re-allocation/copy operations. can go 1 stage better though. vector constructor takes argument allows specify size @ time of instantiation. avoid need reserve() in first place. (be aware need understand difference between resize() , reserve(), 1 affects capacity, other creates vector of specified size)
you need aware of fact if create vector of specified size, size() of vector of size, if have inserted far fewer elements. (you'll using operator[] access , insert elements)
the other question should ask this: if you've got data contained within array, purpose of moving dynamic container , need to?
Comments
Post a Comment