Anatoly Lubarsky

Logo
MSSQL, .NET, Design. Life and Music

Reducing Memory Footprint of any Process with EmptyWorkingSet

Ever wondered why does .NET winform application takes so much memory on startup ? It is obvious that most of this memory is not in use. The reason is that JIT compiler and the whole winforms engine is loaded into the process. However it is possible to remove as many pages as possible from the working set of the specified process using EmptyWorkingSet from psapi.dll.


[DllImport("psapi.dll")]
static extern int EmptyWorkingSet(IntPtr hwProc);

From managed code we can use it like so (for the current process):


static void ClearMemory()
{
    EmptyWorkingSet(Process.GetCurrentProcess().Handle);
}

However it is possible to use this function for any process which handle must have the PROCESS_QUERY_INFORMATION and PROCESS_SET_INFORMATION access rights. Be careful using EmptyWorkingSet since the process will allocate the memory again in the future when needed.


Related Posts:

Sunday, April 20, 2008 9:07 PM

Comments

# Interesting Finds: April 21, 2008

4/21/2008 8:10 AM by Jason Haley

# re: Reducing Memory Footprint of any Process with EmptyWorkingSet
Caveat emptor: I wouldn't be doing this because this is yet another scenario where the OS probably knows better than you. This is especially so when the process is started. The OS prefetcher works hard to ensure you will have the pages you need in physical memory, and then you tell the system to flush them.

Fortunately, the OS is smart enough to ignore this entirely if it seems fit.

4/21/2008 5:28 PM by Sasha Goldshtein

# re: Reducing Memory Footprint of any Process with EmptyWorkingSet
@Sasha Goldshtein

this trick is mainly targeted for those who know what they do :)
therefore I write: "be careful".

4/21/2008 5:35 PM by Anatoly Lubarsky

If your feedback doesn't appear right away, please be patient as it may take a few minutes to publish.

Post a Comment

Protected by CAPTCHAEnter the code you see
Name (*)  
E-mail (*)  
Url
Remember

Comment (*)