I have tested the two option with quite large files.
The std::reverse(ss.begin(), ss.end());
corresponds to the first option (no copy)
The ss_r = new std::string(ss.rbegin(), ss.rend());
corresponds to the second option (copy)
#include <iostream>
#include <fstream>
#include <chrono>
#include <string>
#include <algorithm>
//Just for reading the file
std::string read_file(char * file_name)
{
std::ifstream file(file_name);
std::string ss;
file.seekg(0, std::ios::end);
std::cout << file.tellg() <<std::endl;
ss.resize(file.tellg());
file.seekg(0, std::ios::beg);
file.read(&ss[0], ss.size());
file.close();
return ss;
}
//The real test
int main(int arg, char ** args)
{
std::string ss = read_file(args[1]);
std::string * ss_r=NULL;
std::chrono::time_point<std::chrono::high_resolution_clock> start, end;
start = std::chrono::high_resolution_clock::now();
if(args[2]==std::string("copy"))
{
//Second option
ss_r = new std::string(ss.rbegin(), ss.rend());
}
else
{
//First option
std::reverse(ss.begin(), ss.end());
}
end = std::chrono::high_resolution_clock::now();
int elapsed_nano_seconds = std::chrono::duration_cast<std::chrono::nanoseconds>
(end-start).count();
if(ss_r!=NULL)
{
std::cout<<*ss_r<<std::endl;
}
else
{
std::cout<<ss<<std::endl;
}
std::cout << elapsed_nano_seconds<<std::endl;
}
Testing with icpc test.cpp -O3 --std=c++11
a.out Test_file no_copy runs in 160 microseconds
a.out Test_file copy runs in 320 microseconds
On the other hand with the first option you lost the original string...
So in summary if you don't care about loosing the original string go with std::reverse
if you want to keep it go with std::string(ss.rbegin(), ss.rend());