Pros and Cons of using SetProcessWorkingSetSize

The only good use case I've seen for this call is when you KNOW your process is going to hog a lot of the system's RAM and you want to reserve it for the duration. You use it to tell the OS "Yes, I'm going to eat a lot of the system RAM during my entire run and don't get in my way".

In that situation, leaving the OS's default behavior in place is bad. The OS allocates a default # of MB of RAM to each process- basically its workspace. Its resource management heuristics aren't oracles, so if they detect some process eating way more than its share of system resources (like RAM), they'll try to claw back as much of the excess as possible. For YOUR process this means the OS will waste a lot of CPU (and therefore hurt your performance) by paging memory in and out of your address space when it doesn't need to.


We have found out that, for a GUI application written in Delphi for Win32/Win64 or written in a similar way that uses large and heavy libraries on top of the Win32 API (GDI, etc), it is worth calling SetProcessWorkingSetSize once.

We call it with (... -1, -1) parameters, within a fraction of second after the application has fully opened and showed the main window to the user. In this case, the SetProcessWorkingSetSize(... -1, -1) releases lots of startup code that seem to not be needed any more. The memory quickly restores to about 1/3 of what it would have been without the SetProcessWorkingSetSize(... -1, -1), and does not grow more since then (unless the application allocates more memory). So we have effectively saved 2/3 of the memory of mostly startup code (loading and parsing of configuration files, initializing GUI, etc) that would not be needed to continue running the application.

If you have a GUI application, you may test on your own application the same way - just call SetProcessWorkingSetSize once and see how many memory have been released definitely.

Even for a server (service) application that don't have GUI - I think that calling SetProcessWorkingSetSize once after the server has fully loaded and initialized might have been useful.


SetProcessWorkingSetSize() controls the amount of RAM that your process uses, it doesn't otherwise have any affect on the virtual memory size of your process. Windows is already quite good at dynamically controlling this, swapping memory pages out on demand when another process needs RAM. By doing this manually, you slow down your program a lot, causing a lot of page faults when Windows is forced to swap the memory pages back in. SetProcessWorkingSetSize is typically used to increase the amount of RAM allocated for a process. Or to force a trim when the app knows that it is going to be idle for a long time. Also done automatically by old Windows versions when you minimize the main window of the app.

No need to pinvoke this btw, you can use the Process.GetCurrentProcess.Min/MaxWorkingSet properties.