Free Memory by dropping caches

I found this cool tip today from Avishay Traeger at linux-mm.org about how to free memory by dropping the system caches.

Kernels 2.6.16 and newer provide a mechanism to have the kernel drop the page cache and/or inode and dentry caches on command, which can help free up a lot of memory. Now you can throw away that script that allocated a ton of memory just to get rid of the cache...

To use /proc/sys/vm/drop_caches, just echo a number to it.

To free pagecache:

# echo 1 > /proc/sys/vm/drop_caches

To free dentries and inodes:

# echo 2 > /proc/sys/vm/drop_caches

To free pagecache, dentries and inodes:

# echo 3 > /proc/sys/vm/drop_caches

As this is a non-destructive operation and dirty objects are not freeable, run sync first!

Here are the before and after results from my desktop:

# free
             total       used       free     shared    buffers     cached
Mem:       2074840    1656052     418788          0     140108     907920
-/+ buffers/cache:     608024    1466816
Swap:      3911816      76436    3835380

# sync ; echo 3 > /proc/sys/vm/drop_caches ; free
             total       used       free     shared    buffers     cached
Mem:       2074840     698472    1376368          0        268     126488
-/+ buffers/cache:     571716    1503124
Swap:      3911816      76436    3835380