I want to know which of these two blocks runs faster:
std::string tempMsg( 13000, '\0' ); // constructs the string with a 13000 byte buffer from the start
tempMsg.clear( ); // clears those '\0' chars to free space for the actual data
or
std::string tempMsg; // default constructs the string with a 16-byte buffer on the stack??
tempMsg.reserve( 13000 ); // reallocates the string to increase the buffer size to 13000 bytes??
So I have the following program:
#include <iostream>
#include <string>
#include <chrono>
int main()
{
using std::chrono::high_resolution_clock;
using std::chrono::duration;
auto t1 = high_resolution_clock::now();
// std::string tempMsg( 13000, '\0' ); // constructs the string with a 13000 byte buffer from the start
// tempMsg.clear( );
std::string tempMsg; // default constructs the string with a 16-byte buffer on the stack??
tempMsg.reserve( 13000 );
auto t2 = high_resolution_clock::now();
/* Getting number of milliseconds as a double. */
duration<double, std::milli> ms_double = t2 - t1;
std::cout << ms_double.count() << "ms";
return 0;
}
Is this kind of benchmarking going to give me some worthy results? Or is it flawed and misleads me with unrealistic results?
Also by comparing the results, I saw ~%50 less time consumed by using the second block (the one which calls std::string::reserve
). So does this mean the 2nd solution runs ~%50 faster?