From: Garance A Drosehn Date: 2007-02-17T04:46:40+09:00 Subject: Re: Does it make sense to flush and close? ------=_Part_6029_16048214.1171655193173 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit Content-Disposition: inline On 2/15/07, Mischa Berger wrote: > > 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? > > 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. -- Garance Alistair Drosehn = drosihn@gmail.com Senior Systems Programmer Rensselaer Polytechnic Institute; Troy, NY; USA ------=_Part_6029_16048214.1171655193173--