I'm reading Scott's book effective modern c++. In item 26, there's an example that I wrote on Wandbox: https://wandbox.org/permlink/6DKoDqg4jAjA9ZTB
I want to verify how much the good code is better than the bad one. However, the performance comparison is not what I expected, even the good one is slower that the bad one. I don't know what's going wrong.
To prevent wandbox's code from disappearing, here's the code:
#include <iostream>
#include <chrono>
#include <cstdlib>
#include <set>
#include <string>
using namespace std;
std::multiset<std::string> names;
void bad_logAndAdd(const std::string& name) {
auto now = std::chrono::system_clock::now();
names.emplace(name);
}
template <typename T>
void good_logAndAdd(T&& name) {
auto now = std::chrono::system_clock::now();
names.emplace(std::forward<T>(name));
}
void bad() {
for (int i=0; i<1000000; i++) {
string petname("cs");
bad_logAndAdd(petname);
bad_logAndAdd(std::string("abc"));
bad_logAndAdd("dog");
}
}
void good() {
for (int i=0; i<1000000; i++) {
string petname("cs");
good_logAndAdd(petname);
good_logAndAdd(std::string("abc"));
good_logAndAdd("dog");
}
}
int main()
{
auto begin = std::chrono::high_resolution_clock::now();
bad();
auto end = std::chrono::high_resolution_clock::now();
std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(end-begin).count() << std::endl;
auto begin2 = std::chrono::high_resolution_clock::now();
good();
auto end2 = std::chrono::high_resolution_clock::now();
std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(end2-begin2).count() << std::endl;
}