Should I use swap on Linux?
Monday, 21 February 2022
TL;DR: I turned off swap on my machine and it’s been fine.
I haven’t been able to find clear guidance on whether I should use swap or not on my machine, and if so, how much to set. There are some arguments in favor of using swap that I’ve not been able to fully understand, essentially saying that swap lets you have more useful pages in memory because less useful pages can be swapped out.
But what does that really mean? If I have 20 GB of RAM and 4 GB of swap on a hard drive, isn’t that worse than just adding another 4 GB of RAM and having no swap? And if I have 24 GB of RAM, are you going to tell me I still need swap?
My total RAM + swap will forever be finite, and at some point I will run out of memory. And if I’m to believe that having swap is “a method of increasing equality of reclamation”, what if I put my swap in RAM? That sounds silly, but if simply adding 4GB more RAM is not better than having 4GB more swap, then isn’t that true?
So where are the benchmarks? And how would you even benchmark something like this? My use case as a desktop user is certainly different from a constantly loaded server, but here are the very real downsides to me using swap:
- Hard drive wear is real. Flash memory wears down, and spinning disks cannot rest if they are constantly asked for swap.
- The out-of-memory (OOM) case is ridiculously painful. Without swap, the offending process (usually a runaway program) gets killed. With swap, my entire computer grinds to a halt and becomes unresponsive until the offending process has managed to fill up the swap as well. That could take 10 minutes or longer.
Turning off swap means that any process that uses too much memory is immediately killed. That sounds bad except it would have gotten killed even if I did have swap, just much later.
And after turning off swap, I haven’t noticed any performance hits at all. In fact, performance has been better because idle processes don’t get pushed into swap during times of high memory pressure, so I don’t need to incur the penalty of swapping them back in (the infamous alt-tab-is-slow-because-of-swap problem).
If you’re still using swap on your desktop machine out of superstition, try turning it off. Maybe you don’t need it.