Create zRam a Memory Compression on Arch Linux

zRam is a virtual memory compression using block devices named /dev/zram using a fast compression algorithm that compress the least recently used (LRU) or inactive space in the memory allows the GNU/Linux kernel to free up more memory with less performance hit.

zRam is greatly increasing the available amount of memory without swap disks/partition. It is recommended for user to use zRam instead of not use swap or swap on slow disks.

Create a zRam block devices

Load the zRam modules to the kernel using modprobe:
sudo modprobe zram
Set the zRam extremely fast compression algorithm using lz4:
sudo sh -c "echo 'lz4' > /sys/block/zram0/comp_algorithm"
Set 2 Gigabyte available zRam disk space for swap:
sudo sh -c "echo '2G' > /sys/block/zram0/disksize"
Create a swap on zRam block devices:
sudo mkswap --label zram0 /dev/zram0
Enable the zRam block devices for swapping with high priority:
sudo swapon --priority 100 /dev/zram0

Automatically activate zRam swap at startup

Create a systemd service (zram.service) using a text editor such as nano:
sudo nano /etc/systemd/system/zram.service
Add following to the zram.service:
Description=zRam block devices swapping 
ExecStart=/usr/bin/bash -c "modprobe zram && echo lz4 > /sys/block/zram0/comp_algorithm | echo 2G > /sys/block/zram0/disksize && mkswap --label zram0 /dev/zram0 && swapon --priority 100 /dev/zram0" 
ExecStop=/usr/bin/bash -c "swapoff /dev/zram0 && rmmod zram" 
Enable the zram.service to automatically run at startup:
sudo systemctl enable zram

Disable zRam block devices

Disable the zRam block devices swapping:
sudo swapoff /dev/zram0
Remove the zRam module from the kernel:
sudo rmmod zram
Disable the zram.service from automatically run at startup:
sudo systemctl disable zram.service

See also

  1. Zram or zswap section (Maximizing Performance) - ArchWiki
  2. zram: Compressed RAM based block devices - Linux Kernel Documentation
  3. Image by TobiasDCC0 Public Domain