From 50ef2216fa89c2ebddbe741dd4f27803dd66e664 Mon Sep 17 00:00:00 2001 From: Andreas Kling Date: Wed, 28 Aug 2019 19:32:45 +0200 Subject: [PATCH] GTextEditor: Optimize write_to_file() with ftruncate() Compute the final file size and ftruncate() the destination file to the right size immediately instead of incrementally appending to it. This kind of optimization belongs in the kernel, but until we have it there, this makes saving text files a whole lot faster. :^) --- Libraries/LibGUI/GTextEditor.cpp | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/Libraries/LibGUI/GTextEditor.cpp b/Libraries/LibGUI/GTextEditor.cpp index f005e8fdc6..b7f8beca9d 100644 --- a/Libraries/LibGUI/GTextEditor.cpp +++ b/Libraries/LibGUI/GTextEditor.cpp @@ -992,6 +992,20 @@ bool GTextEditor::write_to_file(const StringView& path) perror("open"); return false; } + + // Compute the final file size and ftruncate() to make writing fast. + // FIXME: Remove this once the kernel is smart enough to do this instead. + off_t file_size = 0; + for (int i = 0; i < m_lines.size(); ++i) + file_size += m_lines[i].length(); + file_size += m_lines.size() - 1; + + int rc = ftruncate(fd, file_size); + if (rc < 0) { + perror("ftruncate"); + return false; + } + for (int i = 0; i < m_lines.size(); ++i) { auto& line = m_lines[i]; if (line.length()) {