How to clear the swap space to speed up your Linux machine

If you just needed the commands

1) Close some programs to free up memory

2) sudo swapoff -a

3) Wait for the swap space to clear

4) sudo swapon -a


Why you should clear the swap space

    When your RAM is insufficient for your computer's memory needs in a given moment, it starts using a piece of the hard drive, called the "swap space," in lieu of RAM. While it has some legitimate uses in ensuring that your computer runs in a period of high demand, it also tends to slow the computer down a lot. And in some cases, even after closing a few programs the swap will still be active, slowing your computer down!

If you're running Xubuntu or one of the other *buntus, then there is a great system load monitor that looks like this:

Swap space

The cpu/mem/swap show the amount of processor, memory, and swap load, respectively. It will also show you the numerical value if you mouse over, and it's often a great start for debugging why your computer is slow, or why it crashes when you run a certain program (for example, some video editors will eat up gigabytes of memory in seconds). When you start using more than half of your memory, some of the demand may start shifting over to swap space. In the case below, I deliberately overloaded the computer with 10 Youtube videos and two office programs:

Swap space

While only a tiny amount of swap has been used, the high memory demand was overflowing to swap, and my computer was already slowing down quite a bit. So, I closed some programs, but the swap was still active, and my remaining programs were still slow! So, at this point I opened the terminal and put in "sudo swapoff -a"

Swap space

Note that active space=total space now. Here, the system is moving all of the swap load back to the RAM. Once it's done (it may take a few minutes), I typed in "sudo swapon -a" to turn the swap back on:

Swap space

And here we are, back where we started! You may ask why you should use the swap at all, since it slows downt he computer when it comes into active use. The reason is because swap is kind of like flood control; if it is deactivated (sudo swapoff -a) and left off, then the computer may crash or slow dramatically when it is short on RAM.

Also, if you leave your computer on a long time, swap may build up slowly over long periods. On Windows the computer would simply freeze or crash, and you would reboot it every few days, so any swap-like issues on Windows woudl be solved by rebooting. But on a Linux machine, I can have my machine on for months at a time since a Linux box is usually far more stable than Windows, so using the swapoff and swapon commands is more a kind of maintenance to keep my machine running as long as I need it.