What is swap memory?

I am using RAM for storing some of my database tables and the others are stored in hard disk.

Today I came to know that my processes are using swap memory. Now what is swap memory and how can I detect that which process is using swap memory and how can i stop them from using it?


Solution 1:

If you run out of physical memory, you use virtual memory, which stores the data in memory on disk. Reading from disk is several orders of magnitude slower than reading from memory, so this slows everything way down. (Exchanging data between real memory and virtual memory is "swapping". The space on disk is "swap space".)

If your app is "using swap", then you either need to use less memory or buy more RAM.

(Swap is useful because applications that aren't being used can be stored on disk until they are used. Then they can be "paged in" and run normally again. While it is not in memory, though, the OS can use that memory for something else, like disk cache. So it's a very useful feature, but if you don't have enough physical memory to run your program, you definitely need more memory. Fortunately, memory is really really cheap these days.)

Solution 2:

A computer has a certain amount of physical memory. But most of the time we want more. So we swap some memory on disk.

Each time we need that memory it needs to be swapped back into memory (swapping some other piece out). There are extremely intelligent algorithms to minimize the delay, but still sometimes we have to wait.

On windows, if you look at the task manager, you can show the column page faults. This shows the number of time, an application asks for a piece of memory that was on the disk and needs to be swapped. Lots of page faults = slow application.

This process is used on several levels. A summary from fast to slow:

  • On the CPU level, there are registers. These are the fastest memory but the amount is limited.
  • Also on the CPU there is a small memory cache. Here a small piece of the running program is stored for fast access. Search on branch predicting algorithms if you want to know more.
  • Sometimes there are level 2 caches between the CPU and the main memory.
  • Next level is the main memory (RAM).
  • Last level and slowest of all is the disk, sometimes you can use USB sticks as extra memory.