Say I have total RAM memory of 1GB , HD of 10 GB with 250 MB swap space

Say I have two files(f1 and f2) each of 500 MB opened on my my laptop. Now both files are in memory and have consumed 1 GB of RAM. Currently f2 is in front of me. Now I start writing in f2 with 100 MB of characters.

Now will OS will swap space here and write 100 MB from f1 to hard disk . When I will switch f1 then OS will bring back those 100 MB of space and put 100 MB of f2 in hard disk.

I there will be lot of other intricacies but just wanted to understand high level fundamentals of how swap space works. Is my understanding correct here ?

  • You left out one thing. If the two loaded files eat up your total ram the swap space has already been used because your OS has to live somewhere. Aug 24, 2019 at 17:48
  • Most likely, your application will use mmap (or whatever the equivalent is on your operating system) to map the files into the process's virtual memory space, and thus the two open files will not use any RAM at all (well, they will use a couple of bytes for some metadata, but that's it). Aug 24, 2019 at 18:06
  • @candied_orange You are right. But to understand the concept and make it simpler assume OS is not taking any memory hypothetically Aug 24, 2019 at 18:14
  • 1
    @user3198603 seems like leaving that out just adds to the confusion. You could have simply said 1GB total was the all that can be used for these loaded files. Aug 24, 2019 at 18:19
  • 1
    You might find this useful.
    – Blrfl
    Aug 24, 2019 at 19:56

1 Answer 1


Forget about having large files. Just say you have an object of 500 MB, another object of 500 MB, and you want to add 100 MB to the second object. And we ignore the fact that OS, code, and other applications also need space.

The OS will not care about the objects. It will just pick 100 MB of RAM that haven't been used for a while, write them to the swap space, and have 100 MB available for your new additions.

If you examine both objects, since they are 1100 MB and only 1000 MB are in RAM, you will always run into situations where you try to read memory not in RAM. At that point, some other memory is written to the swap file, and the missing memory loaded.

Depending on your algorithms, you may run into a situation where RAM is always written to the swap file just before it is accessed and is read again, which would be the worst case. If that happens, you either suffer from very inefficient execution, or you have to change your algorithms.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.