Saturday, January 5, 2008

How much a Thread cost you?

I was recently wondering if creating n number of threads will affect the memory usage of an application. I created a sample application which created a thread on a button click to observe the memory usage on each thread creation. The thread proc as such did nothing; I had put a sleep statement in it so that the thread is alive and is using the memory for some time while I am creating some more threads.

I was relaxed to see that the memory usage in task manager rose by just 20K -30 K on each thread creation with an exception that the first thread creation increased the memory by around 1 MB.


Later I started checking Virtual memory usage as well and was shocked to see 1 MB of memory usage on each thread creation! A little goggling revealed that by default each thread is assigned a 1 MB stack! Check out the sample code which prints out the Virtual Memory usage of the test application in debug window on each thread creation.

//code
private static void Somethread()
{
Debug.WriteLine(string.Format("Started thread with thread id {0}", Thread.CurrentThread.ManagedThreadId));
//Print task managers VM Size column
Debug.WriteLine(string.Format("Current VM usage is {0} MB", (Process.GetCurrentProcess().PagedMemorySize64 / (1024 * 1024))));

Thread.Sleep(1000 * 60 * 1); // let the thread live for some time while we create some more threads
Debug.WriteLine(string.Format("----Ended thread with thread id {0}", Thread.CurrentThread.ManagedThreadId));

//Print task managers VM Size column
Debug.WriteLine(string.Format("Current VM usage is {0} MB", (Process.GetCurrentProcess().PagedMemorySize64 / (1024 * 1024))));

}

private void btnCreateThread_Click(object sender, EventArgs e)
{
//Each created thread will be allocated 1 MB of Virtual memory
Thread samplethread = new Thread(Somethread);
samplethread.IsBackground = true;
samplethread.Start();
}

Conclusion: Want to keep a small footprint of the application, think twice before creating a new thread.

1 comment:

jaykavi said...

Nice article. I tried to run the code and found the same result. In .Net 2.0 the initial stack size of creating Threads is 1 MB. While you create the Thread, you can set the stack size like this way:
Thread samplethread = new Thread(Somethread,51200);

But the stack size should be appropriate and not any random value because it may cost more memory.