c++ - What is better: reserve vector capacity, preallocate to size or push back in loop? -
i have function takes pointer char array , segment size input arguments , calls function requires std::array<std::string>
. idea input char array "sectioned" equal parts, , string array formed.
the input char array format several smaller arrays (or strings) of determined size, concatenated togeather. these not assumed zero-terminated, although might be. examples segment size 5 , number of elements 10:
char k[] = "1234\0001234\0001234\0001234\0001234\0001234\0001234\0001234\0001234\0001234\000"; char m[] = "1234\00067890987654321\000234567809876\0005432\000\000\0003456789098"; char n[] = "12345678909876543211234567890987654321123456789098";
length of char arrays 51 (segment * elements + 1). goal make function use resources efficiently, importantly execution time.
since there many ways skin cat, have 2 (or three) ways tackle this, , question is, "better"? mean faster , less resource-wasteful. not professional, patient me.
here, values
preallocated , each string assigned value.
void myfnc_1(void *a_src, uint32_t a_segment) { // a_segment = 5 example size_t nsize = getsize(); // method, gets 10 std::vector<std::string> values(nsize); char* v = a_src; // take k, n or m example (size_t = 0; < nsize; ++i) { values.at(i).assign(v, a_segment); v += a_segment; } }
here, vector not allocated, each iteration new string added.
void myfnc_1(void *a_src, uint32_t a_segment) { size_t nsize = getsize(); std::vector<std::string> values(); char* v = a_src; (size_t = 0; < nsize; ++i) { values.push_back(""); values.back().assign(v, a_segment); v += a_segment; } }
there might third way, that's better. i'm not experienced vectors don't know exactly. segment length , number of elements make difference if large (5, 10) or small (100, 10000)?
first post, big fan :)
better performance reached when avoiding dynamic reallocation, try have vector memory big enough receive elements.
your first solution more efficient because if nsize bigger default vector capacity, second 1 need reallocation able store elements.
as commented melkon, reserve
better:
void myfnc_1(void *a_src, uint32_t a_segment) { size_t nsize = getsize(); std::vector<std::string> values; values.reserve( nsize ); char* v = a_src; (size_t = 0; < nsize; ++i) { values.push_back( std::string( v, a_segment ) ); v += a_segment; } }
Comments
Post a Comment