You can also set your "swappiness" value from the default of 60, this way the swap won't grow so large to begin with. Why the shipping default is set to 60 when the recommended value is 10 perplexes me. From the Ubuntu SwapFAQ:
The default setting in Ubuntu is swappiness=60. Reducing the default value of swappiness will probably improve overall performance for a typical Ubuntu desktop installation. A value of swappiness=10 is recommended, but feel free to experiment.
By changing this value to 10 or even 0, you can add a significant & perceivable speed boost to an older system with a slow drive. Note that setting this value to 0 does not turn swap off, it just sets it to the least aggressive swap setting and avoids hitting the disk until absolutely necessary.
I see no reason not to set this to 0 since anything that hits disk is slower than RAM. I have a 8 virtual cores, a fast SSD & 8 GB of memory and my swap is set to 0. As of this moment I have 3 virtual machines running, my memory usage is 7.1 of 7.7 GB, my used swap is only at 576KB of 952MB and all systems are running smoothly!
From the Ubuntu SwapFAQ:
The swappiness parameter controls the tendency of the kernel to move processes out of physical memory and onto the swap disk. Because disks are much slower than RAM, this can lead to slower response times for system and applications if processes are too aggressively moved out of memory.
- swappiness can have a value of between 0 and 100
- swappiness=0 tells the kernel to avoid swapping processes out of physical memory for as long as possible
- swappiness=100 tells the kernel to aggressively swap processes out of physical memory and move them to swap cache
Below are basic instructions for checking swappiness, emptying your swap and changing the swappiness to 0:
To check the swappiness value:
To turn swapoff (as suggested by SpamapS):
This will empty your swap and transfer all the swap back into memory. First make sure you have enough memory available by viewing the resources tab of gnome-system-monitor, your free memory should be greater than your used swap. This process may take a while, use gnome-system-monitor to monitor and verify the progress.
sudo swapoff -a
To set the new value to 0:
echo 0 | sudo tee /proc/sys/vm/swappiness
To turn swap back on:
sudo swapon -a