Prevent vector reallocations by preallocating known sizes#127
Conversation
| throw std::out_of_range("Trying to read out of range of buffer"); | ||
| } | ||
| std::vector<T> result(reinterpret_cast<T*>(&buffer[position]), reinterpret_cast<T*>(&buffer[position]) + size); | ||
| std::vector<T> result(size); |
There was a problem hiding this comment.
Isn't this an extra initialization of the data?
std::vector<T> result(size); allocates size elements and value initializes them and then we copy them in.
The previous one would skip the value initialization?
There was a problem hiding this comment.
What worries me here is that the iterator-based approach won't know to preallocate the correct size, so it would then resize the vector multiple times, actually not completely sure about this one
There was a problem hiding this comment.
I checked the implemention (MSVC STL) and it will do one allocation when it's supplied with two iterators. So this would unfortunately be a pessimization.
| } | ||
| } | ||
|
|
||
| return BinaryReader(std::move(buffer)); |
There was a problem hiding this comment.
Could you expand a bit on why the above would be faster/better?
There was a problem hiding this comment.
Similar idea as with the binary_reader, preallocating the vector of the full size to avoid any re-allocating.
To be fair I might be going off on an unconfirmed suspicion that the iterator approach will realloc
There was a problem hiding this comment.
Okay, I did some research and this could theoretically be faster. I'm not sure if it is though so perhaps a benchmark would be a good idea.
No description provided.