GNOME Bugzilla – Bug 165954
get_contents_stdio's initial "str"
Last modified: 2011-02-18 16:14:20 UTC
get_contents_stdio should wait until after the first fread before allocating "str". That way, any file less than the buffer size can be allocated precisely without the need for a realloc.
Without the need for several reallocs. It takes 5 reallocs to enlarge str to the size of the read buffer. If the first memory allocation would be delayed until after the read, we could save these reallocs for most files.
Created attachment 37030 [details] [review] delay malloc until after the first read
This patch changes get_contents_stdio() so that: - If the first read is shorter than the size of the read buffer, allocate exactly the number of read bytes + 1. - Otherwise allocate 2048 bytes (the size of the read buffer). The patch also adds a simple unit test for g_file_get_contents(). BTw, shouldn't the size of the read buffer be increased to 4096 bytes? On most systems that should be a better estimate of the block size of the underlying file system.
Looks fine to me; bumping the buffer size to 4k sounds fine too.
Committed to the HEAD branch, closing as FIXED. 2005-03-10 Sven Neumann <sven@gimp.org> * glib/gfileutils.c (get_contents_stdio): delay memory allocation until after the first read. Saves a bunch of reallocs. Also increased the buffer size to 4096 bytes. (bug #165954) * tests/file-test.c (test_get_contents): added a (very basic) test for g_file_get_contents().