3 ms·
From the article, the proposed change: -3,6 +3,8 std::vector<std::string> tokenize(const std::string& s) { std::vector<std::string> resul
by Karellen 4y ago
From the article, the proposed change:
-3,6 +3,8
std::vector<std::string> tokenize(const std::string& s)
{
std::vector<std::string> result;
+ // Expect four fields or less in our input.
+ result.reserve(4);
std::string::size_type f = 0;
std::string::size_type p = s.find(':');
I wonder why not:
-3,6 +3,7
std::vector<std::string> tokenize(const std::string& s)
{
- std::vector<std::string> result;
+ // Expect four fields or less in our input.
+ std::vector<std::string> result(4);
std::string::size_type f = 0;
std::string::size_type p = s.find(':');
?
It's not a big difference, but vectors have a constructor that takes an initial reservation size in order to facilitate pre-allocation.
Edit: No it doesn't. I've not written C++ in anger in... actually quite a bit longer than I thought. And it shows. Doh. Thanks, wirelessgigabit.
- woodruffw 4y agoAt `-O1` and higher, `clang` recognizes the `reserve()` pattern and turns it into the reserving constructor[1]. GCC does the same[2]. [1]: https://godbolt.org/z/Tjazsd686 https://godbolt.org/z/Tjazsd686 [2]: https://godbolt.org/z/7nWEe1d4b https://godbolt.org/z/7nWEe1d4b
- WirelessGigabit 4y agoNot the same. Your version creates a vector with 4 times the default of std::string. #include <string> #include <iostream> #include <vector> template < typename T > std::ostream & operator<< (std::ostream & s, const std::vector < T > &v) { s.put ('['); char comma[3] = { '\0', ' ', '\0' }; for (const auto & e:v) { s << comma << e; comma[0] = ','; } return s << ']'; } int main () { std::vector < std::string > with_reservation; with_reservation.reserve (4); std::cout << "with_reservation: " << with_reservation << std::endl;; std::vector < std::string > via_ctor (4); std::cout << "via_ctor: " << via_ctor << std::endl;; return 0; } Yields with_reservation: [] via_ctor: [, , , ] https://onlinegdb.com/GUlVHoqC5z https://onlinegdb.com/GUlVHoqC5z