简体   繁体   中英

std::vector<char> VS std::string, which one is faster?

I've been messing around with cellular-automata for a while now, and the way I chose to implement them is by creating a 2D vector of cells, where each cell was initially a vector of integers itself (because I want each cell to store more than one value) , which I later changed to short unsigned integers, and then to chars, because I realized the smallest data type is more than enough for my needs...

I'm currently looking for ways to improve performance, and it got me thinking, would it be better optimization-wise if I replaced the vector of chars with a string?

Knowing that the entire matrix always has a fixed size, meaning the size of the 2D grid as well as that of each cell is allocated from the beginning and is unchanging for the duration of the program's runtime:

Which one is faster to access? Modify? Copy? Or preform general operations on?

Also, I know I said everything has a fixed size, but just for future reference, according to my surface-level knowledge of vectors, a vector has to be re-allocated everytime you push_back() a new element into it, is that the case with strings?

which one is faster?

Depends. Either one, depending on how you use them. You can find out whether one is measurably faster than the other by... measuring.

They both use fundamentally the same abstract data structure, and have the same asymptotical complexity for all operations.

according to my surface-level knowledge of vectors, a vector has to be re-allocated everytime you push_back()

Your knowledge is incorrect. A std::vector has to only be reallocated when the capacity of the vector is exceeded , which isn't everytime you push_back. Same appilies to std::string

From this response https://stackoverflow.com/a/25581325/15824294 I think we can observe that string is faster than vector with both g++ and clang++

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM