How To Clear Cache in Linux

January 4, 2024 / How-to Guide

Linux, similar to other operating systems, uses caching to optimise system performance. Although Linux efficiently manages memory, there are scenarios, like system diagnostics or application tests, where manual clearing of caches could be advantageous.

In this guide, we will explore how to clear various caches in Linux, including memory, swap, and buffer.

Small Instructions:

  1. How to Clear PageCache, dentries, and inodes:
    $ sync && echo 3 > /proc/sys/vm/drop_caches
  2. How Clear Swap space:
    $ swapoff -a && swapon -a

Detailed Instructions:

  • PageCache: It improves file I/O performance by storing often-used file data in RAM.
  • Dentries help you to speed up file name searches by storing cached directory entries.
  • Inodes stores important metadata about files and directories, it also separates from the content or names.

How to Clear PageCache, dentries, and inodes

The Linux kernel offers a way to clear the cache without restarting. Here are the available options:

  1. How to Clear PageCache:
    $ echo 1 > /proc/sys/vm/drop_caches
  2. How to Clear dentries and inodes:
    $ echo 2 > /proc/sys/vm/drop_caches
  3. How to Clear PageCache, dentries, and inodes:
    $ echo 3 > /proc/sys/vm/drop_caches

    Note: When running the mentioned commands, make sure you have root privileges.

Free Up Swap Space

When your computer’s memory is full, it uses swap space. If you want to clear it:

  1. Turn off swap:
    $ swapoff -a

    This command disables all swap files and partitions, shifting swap contents back into the main memory.

  2. Turn on swap again:
    $ swapon -a

    This command enables all swap files and partitions mentioned in /etc/fstab.

Buffer Cache

As mentioned before, PageCache is often interchangeable with buffer cache. The buffer cache is a memory area in Linux that stores frequently accessed disk data to enhance system performance. To clear it, follow the instructions in the previous section on clearing PageCache.

Precautions

  • Backup: Back up vital data before clearing caches or making substantial changes.
  • Understand your actions: Clearing caches may cause temporary performance issues. Linux adeptly handles its cache, so unless there’s a specific necessity, it’s generally best to allow the system to manage itself.
  • Monitor system performance: Before and after clearing caches, observe system performance metrics to assess the impact of your actions.

In summary, although Linux is designed to handle memory and caches efficiently, knowing how to manually clear them is an additional tool for system administrators and power users. Whether troubleshooting, testing, or optimising, this capability can be useful in specific scenarios. For more information, visit our knowledge base section.

Spread the love