Ruby's File.open and the need for f.close -
it's common knowledge in programming languages flow working files open-use-close. yet saw many times in ruby codes unmatched file.open calls, , found this gem of knowledge in ruby docs:
i/o streams automatically closed when claimed garbage collector.
darkredandyellow friendly irc take on issue:
[17:12] yes, , also, number of file descriptors limited os
[17:29] assume can run out of available file descriptors before garbage collector cleans up. in case, might want use close them yourself. "claimed garbage collector." means gc acts @ point in future. , it's expensive. lot of reasons explicitly closing files.
- do need explicitly close
- if yes why gc autoclose ?
- if not why option?
i saw many times in ruby codes unmatched
file.open
calls
can give example? ever see in code written newbies lack "common knowledge in programming languages flow working files open-use-close".
experienced rubyists either explicitly close files, or, more idiomatically, use block form of file.open
, automatically closes file you. implementation looks like this:
def file.open(*args, &block) return open_with_block(*args, &block) if block_given? open_without_block(*args) end def file.open_without_block(*args) # whatever ... end def file.open_with_block(*args) yield f = open_without_block(*args) ensure f.close end
scripts special case. scripts run short, , use few file descriptors doesn't make sense close them, since operating system close them anyway when script exits.
do need explicitly close?
yes.
if yes why gc autoclose?
because after has collected object, there no way close file anymore, , leak file descriptors.
note it's not garbage collector closes files. garbage collector executes finalizers object before collects it. happens file
class defines finalizer closes file.
if not why option?
because wasted memory cheap, wasted file descriptors aren't. therefore, doesn't make sense tie lifetime of file descriptor lifetime of chunk of memory.
you cannot predict when garbage collector run. cannot predict if run at all: if never run out of memory, garbage collector never run, therefore finalizer never run, therefore file never closed.
Comments
Post a Comment