From 7a5c92aaeefb24293b1e6cb4a70caa46add933dd Mon Sep 17 00:00:00 2001 From: Thomas Goyne Date: Wed, 30 Apr 2014 06:50:42 -0700 Subject: [PATCH] Speed up TextFileWriter a bit Write the text and the newline separately rather than appending the newline to the text to eliminate a copy of the text. --- src/text_file_writer.cpp | 35 +++++++++++++++++++++++------------ src/text_file_writer.h | 3 ++- 2 files changed, 25 insertions(+), 13 deletions(-) diff --git a/src/text_file_writer.cpp b/src/text_file_writer.cpp index 0e990927e..2a104ae7c 100644 --- a/src/text_file_writer.cpp +++ b/src/text_file_writer.cpp @@ -30,14 +30,23 @@ #include #include +#ifdef _WIN32 +#define NEWLINE "\r\n" +#else +#define NEWLINE "\n" +#endif + TextFileWriter::TextFileWriter(agi::fs::path const& filename, std::string encoding) : file(new agi::io::Save(filename, true)) , ostr(file->Get()) +, newline(NEWLINE) { if (encoding.empty()) encoding = OPT_GET("App/Save Charset")->GetString(); - if (boost::iequals(encoding, "utf-8")) + if (boost::iequals(encoding, "utf-8")) { conv = agi::make_unique("utf-8", encoding.c_str(), true); + newline = conv->Convert(newline); + } try { // Write the BOM @@ -48,7 +57,10 @@ TextFileWriter::TextFileWriter(agi::fs::path const& filename, std::string encodi } } -TextFileWriter::TextFileWriter(std::ostream &ostr) : ostr(ostr) { +TextFileWriter::TextFileWriter(std::ostream &ostr) +: ostr(ostr) +, newline(NEWLINE) +{ WriteLineToFile("\xEF\xBB\xBF", false); } @@ -56,15 +68,14 @@ TextFileWriter::~TextFileWriter() { // Explicit empty destructor required with a unique_ptr to an incomplete class } -void TextFileWriter::WriteLineToFile(std::string line, bool addLineBreak) { - if (addLineBreak) -#ifdef _WIN32 - line += "\r\n"; -#else - line += "\n"; -#endif +void TextFileWriter::WriteLineToFile(std::string const& line, bool addLineBreak) { + if (conv) { + auto converted = conv->Convert(line); + ostr.write(converted.data(), converted.size()); + } + else + ostr.write(line.data(), line.size()); - if (conv) - line = conv->Convert(line); - ostr.write(line.data(), line.size()); + if (addLineBreak) + ostr.write(newline.data(), newline.size()); } diff --git a/src/text_file_writer.h b/src/text_file_writer.h index 0f2ea0feb..c1d7c8726 100644 --- a/src/text_file_writer.h +++ b/src/text_file_writer.h @@ -33,11 +33,12 @@ class TextFileWriter { std::unique_ptr file; std::unique_ptr conv; std::ostream &ostr; + std::string newline; public: TextFileWriter(agi::fs::path const& filename, std::string encoding=""); TextFileWriter(std::ostream &ostr); ~TextFileWriter(); - void WriteLineToFile(std::string line, bool addLineBreak=true); + void WriteLineToFile(std::string const& line, bool addLineBreak=true); };