Change that line to read
std::string textToParse(std::istream_iterator<char>{file},
std::istream_iterator<char>{});
(note the curly braces), and don't use pre-C++11 compiler :-)
(actually I'm not sure it's going to work with VC++ 2012, I used 2013
and got this result:
Method 1 :498549
Method 2 :305819
Method 3 :110364
(with an 18K file, and those are the processor ticks, using the Windows
QueryPerformanceCounter)
How big is your file?
Another note: make sure the optimizer does not throw away the result of
the Method1. It's quite possible that since you're not returning it
anywhere, the optimizer might change the code to never create the object
in the first place. Think of returning the string from those functions
(as in 'std::string Method1(...')
Here is my (corrected) code:
//--------------------------------------------------------------------------------------------------
// Standard Includes
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <cstdio>
#include <Windows.h>
const unsigned int NUM_ITERATIONS = 100;
//--------------------------------------------------------------------------------------------------
std::string Method1()
{
std::ifstream file("test.txt");
if (!file)
{
// Error
throw 1;
}
std::string textToParse(std::istream_iterator < char > {file},
std::istream_iterator < char > {});
file.close();
return textToParse;
}
//--------------------------------------------------------------------------------------------------
std::string Method2()
{
std::ifstream file("test.txt");
if (!file)
{
// Error
throw 22;
}
std::string textToParse;
file >> std::noskipws;
std::copy(std::istream_iterator<char>(file),
std::istream_iterator<char>(),
std::inserter(textToParse, textToParse.begin()));
file.close();
return textToParse;
}
//--------------------------------------------------------------------------------------------------
std::string Method3()
{
std::ifstream file("test.txt");
if (!file)
{
// Error
throw 333;
}
std::stringstream textToParse;
textToParse << file.rdbuf();
file.close();
return textToParse.str();
}
//--------------------------------------------------------------------------------------------------
int main()
{
Method1();
Method2();
Method3();
LARGE_INTEGER t0, t1;
QueryPerformanceCounter(&t0);
for (unsigned count = 0; count < NUM_ITERATIONS; ++count)
{
Method1();
}
QueryPerformanceCounter(&t1);
std::cout << "Method 1 :" << t1.QuadPart - t0.QuadPart << std::endl;
QueryPerformanceCounter(&t0);
for (unsigned count = 0; count < NUM_ITERATIONS; ++count)
{
Method2();
}
QueryPerformanceCounter(&t1);
std::cout << "Method 2 :" << t1.QuadPart - t0.QuadPart << std::endl;
QueryPerformanceCounter(&t0);
for (unsigned count = 0; count < NUM_ITERATIONS; ++count)
{
Method3();
}
QueryPerformanceCounter(&t1);
std::cout << "Method 3 :" << t1.QuadPart - t0.QuadPart << std::endl;
}
//--------------------------------------------------------------------------------------------------