Swap Space and Types of Swap
Swap space is a memory virtualization concept that allows Linux to use disk space as an extension of RAM when the physical memory is full. Swap space can also store data from RAM when the system hibernates. There are two forms of swap space in Linux: the swap partition and the swap file. Let’s see what they are and how they differ.
A swap partition is a dedicated section of the hard disk that is used only for swapping. No other files can reside there. A swap partition is created with a partitioning tool and has a specific type code. To use a swap partition, it needs to be formatted with the mkswap command and activated with the swapon command. A swap partition can be enabled automatically at boot by adding an entry to /etc/fstab.
The advantages of using a swap partition are:
- It can be placed on a contiguous area of the disk, which improves performance on HDDs by reducing seek time and increasing throughput.
- It can be encrypted with dm-crypt for security reasons.
The disadvantages of using a swap partition are:
- It requires a separate disk partition, which may not be available or easy to create on some systems.
- It has a fixed size, which may not be optimal for different workloads or memory demands.
A swap file is a regular file in the filesystem that is used for swapping. It can be created with the fallocate or dd command and has the same format as a swap partition. To use a swap file, it needs to be activated with the swapon command. A swap file can also be enabled automatically at boot by adding an entry to /etc/fstab.
The advantages of using a swap file are:
- It does not require a separate disk partition, which makes it easier to create and manage on some systems.
- It has a flexible size, which can be adjusted according to the needs of the system.
The disadvantages of using a swap file are:
- It may not be contiguous on the disk, which may degrade performance on HDDs by increasing seek time and fragmentation.
- It may not be compatible with some file system features, such as compression, encryption, snapshots, or deduplication.
Recommended Swap Size
The swap size is a portion of the hard disk that is used as additional memory when the RAM is full. The swap size can vary depending on the system and its needs.
A general rule of thumb is to use twice the size of RAM if RAM is less than 2 GB, or size of RAM plus 2 GB if RAM is more than 2 GB. However, this may not be optimal for all situations, and some systems may not need swap at all if they have enough RAM. The following table is another recommendation that is recommended by the Linux Professional Institute.
|Amount of RAM
|Recommended Swap Size