Hyman Rosen said:
There is generally no need to free resources just before program exit,
because the operating system will do that for you - a program which
spends a bunch of time freeing every allocated object and then exits
has just wasted all of that time. It's important to free resources
which can be allocated in an unbounded fashion. That is, a program
should act like a garbage collector - unreachable objects must be
reclaimed, but reachable ones don't need to be.
Okay, first let's talk about C. In C memory allocation and freeing is
not quite fast, so you're indeed making a good point. There is also no
garbage collector, which does that job for you. However, there is still
a very important reason to free your memory. At some point in time you
may want to restructure your program, perhaps to enhance it, at which
point it will get you into trouble. We're talking about safety and
modularity here.
Next thing is that exiting a program, which really allocates millions of
memory blocks generally doesn't need to exit that fast anyway. Also
note that allocating and freeing 5 million (!) blocks of 256 bytes using
malloc/free takes only around 1.6 seconds here (Athlon64 x2 with 2.7 GHz
and 2 GiB of RAM). The program I used can be found at [1].
So still there is no excuse for not freeing memory. And that's just
about memory, but I was talking about all kinds of resources. Not
freeing them will get you into trouble. If you're too convinced (or
lazy) to do it, better stop using C. You're writing unsafe, nonmodular
code, because of conviction (or laziness).
Now let's talk about PHP, which is a garbage-collected language, so you
don't deal with memory anyway, unless you specifically want to (e.g. by
using unset()). But there are a lot of resource types, which are not
covered by the garbage collector like files and database connections.
You should free them for the same reasons as above. You're not doing
anything the PHP runtime wouldn't do by itself, but you're writing safe,
modular code that way, which is hardly slower.
[1]
http://codepad.org/tjlVGJB8
Greets
Ertugrul