tags:

views:

56

answers:

2

Hi,

I have desktop application developed in C#. The VM Size used by application is very high. I want to add watermark to a pdf file, which has more that 10,000 pages, 10776 pages to be exact, the VM size inscreases and some times the application freezes or it throws out of memory exception.

Is there a solution to release / decrease the VM size programatically in C#

+1  A: 

This depends strongly on your source code. With the information given all I can say is that it would be best to get a memory profiler and check if there is space for optimizations.

Just to demonstrate you how memory usage might be optimized I would like to show you the following example. Instead of using string concatenation like this

string x = "";
for (int i=0; i < 100000; i++)
{
    x += "!";
}

using a StringBuilder is far more memory- (and time-)efficient as it doesn't allocate a new string for each concatenation:

StringBuilder builder = new StringBuilder();
for (int i=0; i < 100000; i++)
{
    builder.Append("!");
}
string x = builder.ToString();

The concatenation in the first sample creates a new string object on each iteration that occupies additional memory that will only be cleaned up when the garbage collector is running.

0xA3
My application freezes and sometimes throws out of memory exception
Pavan Navali
+2  A: 

Environment.FailFast :)

In all seriousness though, a large VM size is not necessarily an indication of a memory problem. I always get confused when it comes to the various memory metrics but I believe that VM size is a measurement of the amount of used address space, not necessarily used physical memory.

Here's another post on the topic: http://stackoverflow.com/questions/27407/what-does-vm-size-mean-in-the-windows-task-manager

If you suspect that you have a problem with memory usage in your application, you probably need to consider using a memory profiler to find the root cause (pun intended.) It's a little tricky to get used to at first but it's a valuable skill. You'd be surprised what kind of performance issues surface when you're profiling.

Josh Einstein
Indeed, that's the reason I never trust Task Manager, but always use Sysinternal's Process Explorer, where you can explicitly see the Private Bytes and the VM size.
Patrick
Very true, private bytes is a much more meaningful number.
0xA3
My application freezes and sometimes throws out of memory exception.
Pavan Navali
Yeah then you're going to have to profile to find out where all the memory is going. If you start running out of free contiguous address space you will hit out of memory errors. Large arrays and strings are the most common culprit but you could just be leaking a lot of smaller object references. (Or optionally I suppose you could ignore the problem and move to a 64 bit OS.)
Josh Einstein
@Patrick: From Vista on, Task Manager will show you the private bytes instead of the VM size (as on Win XP).
0xA3