What is swap?
Swap space is the area on a hard disk. It is a part of your machine's Virtual Memory, which is a combination of accessible physical memory (RAM) and swap space. Swap space is used when your operating system decides that it needs physical memory for active processes and the amount of available (unused) physical memory is insufficient. When this happens, inactive pages from the physical memory are then moved into the swap space, freeing up that physical memory for other uses.
So, swap space/memory is useful when you have less space left on your physical memory (RAM). Beware that access time for swap is slower as it is reading from your HDD or SSD.
How much swap do I need?
Ideally, it should be equal to the amount of RAM.
How do I add a swap file?
# Turn swap off
# This moves stuff in swap to the main memory and might take several minutes
sudo swapoff -a
# Create an empty swapfile
# Note that "1G" is basically just the unit and count is an integer.
# Together, they define the size. In this case 8GB.
sudo dd if=/dev/zero of=/swapfile bs=1G count=8
# Set the correct permissions
sudo chmod 0600 /swapfile
# Set up a Linux swap area
sudo mkswap /swapfile
# Turn the swap on
sudo swapon /swapfile
Check if it worked
grep Swap /proc/meminfo
Make it permanent (persist on restarts)
Add this line to the end of your /etc/fstab
:
/swapfile swap swap sw 0 0
And you have now an additional 8GB which can be utilized by your system.
Enjoy!