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. :^)
This commit is contained in:
Andreas Kling 2019-08-28 19:32:45 +02:00
parent 5d3696174b
commit 50ef2216fa

View file

@ -992,6 +992,20 @@ bool GTextEditor::write_to_file(const StringView& path)
perror("open"); perror("open");
return false; 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) { for (int i = 0; i < m_lines.size(); ++i) {
auto& line = m_lines[i]; auto& line = m_lines[i];
if (line.length()) { if (line.length()) {