Hi,

while using the read-file module, I found it can be optimized on
seekable files using the the file length as the initial buffer size; it
avoids some unnecessary reallocations.

Cheers,
Giuseppe



>From 41bc1ff07e437f524cf6cf235b9017aca1ed8a6a Mon Sep 17 00:00:00 2001
From: Giuseppe Scrivano <gscriv...@gnu.org>
Date: Tue, 3 Aug 2010 15:40:19 +0200
Subject: [PATCH] read-file: Avoid memory reallocations with seekable files.

* lib/read-file.c (fread_file): With seekable files, use the file
length as the initial buffer size.
---
 ChangeLog       |    6 ++++++
 lib/read-file.c |   18 ++++++++++++++++++
 2 files changed, 24 insertions(+), 0 deletions(-)

diff --git a/ChangeLog b/ChangeLog
index 4d24a34..64a6042 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,3 +1,9 @@
+2010-08-03  Giuseppe Scrivano  <gscriv...@gnu.org>
+
+       read-file: Avoid memory reallocations with seekable files.
+       * lib/read-file.c (fread_file): With seekable files, use the file
+       length as the initial buffer size.
+
 2010-08-01  Bruno Haible  <br...@clisp.org>
 
        Integrate the regex documentation.
diff --git a/lib/read-file.c b/lib/read-file.c
index 6b655db..b0ceb1f 100644
--- a/lib/read-file.c
+++ b/lib/read-file.c
@@ -38,6 +38,24 @@ fread_file (FILE * stream, size_t * length)
   size_t alloc = 0;
   size_t size = 0;
   int save_errno;
+  long pos;
+
+  if ((pos = fseek (stream, 0, SEEK_CUR)) == 0)
+    {
+      long size;
+
+      if (fseek (stream, 0, SEEK_END) < 0)
+        return NULL;
+
+      size = ftell (stream);
+      if (size < 0 || fseek (stream, pos, SEEK_SET) < 0)
+        return NULL;
+
+      alloc = size + 1;
+      buf = malloc (alloc);
+      if (!buf)
+        return NULL;
+    }
 
   for (;;)
     {
-- 
1.7.1

Reply via email to