Hi everyone, Consider the following code: # Save the file on the file system File.open(self.temp_path, 'wb') do |f| while buff = myfile_field.read(4096) f.write(buff) f.flush end end Is there any benefit in flushing in the code above? Does this mean 4096 bytes of memory are freed everytime flush is called? I'm trying to grasp what exactly happens and if there are any benefits or drawbacks. Thanks, Mischa
on 2007-02-16 00:39
on 2007-02-16 21:17
On Feb 15, 2007, at 14:39, Mischa B. wrote: > end > > Is there any benefit in flushing in the code above? Unlikely. It only ensures the data is written to the file. > Does this mean 4096 bytes of memory are freed everytime flush is > called? No. The GC will clean up memory as necessary. > I'm trying to grasp what exactly happens and if there are any benefits > or drawbacks. fflush(3) is called more often, that's all.
on 2007-02-16 21:47
On 2/15/07, Mischa B. <email@example.com> wrote: > end > end > > Is there any benefit in flushing in the code above? > > I'm trying to grasp what exactly happens and if there are any benefits > or drawbacks. In most situations, the extra calls flush are nothing but a drawback, in that they are a performance penalty. That's why the operating system caches up the writes in the first place -- to speed things up. But in some situations, it might considered a benefit. For instance if you're concerned that the destination might run out of disk space, then it might be to your advantage to *immediately* find out when that happens. Without those extra calls to flush, if you *do* run out of disk space, then the code has no way of knowing how much of the data actually made it to the disk. Consider, for instance, if you were writing a huge file to multiple USB-key devices. If code knew exactly when the first one was full, then it could flip to a new floppy and continue writing. (there are other solutions to that specific example, but it *could* be worthwhile to simply write the data and catch the error when the output device is full). The extra calls to flush could also be a benefit if some other process is monitoring the destination file, just to keep track of how far along the first process is. Someone doing a 'tail -f', for instance. Most of the time it is not worth it to do the calls to flush, especially if you're in a tight loop like the one in your example, but in some special circumstances it can be worth the performance penalty.
on 2007-02-18 09:45
I think the following If you set "file.sync = true" it would do the same and you don't have to write "file.flush" every time you use a "file.write".