System.String Memory Usage

M

miguel

Hi,

I have created a service which parses real-time prices from one format
into another. This is all working very quickly and nicely, however, I
have recently found that the memory usage is astronomical after a few
hours. (1.5-2 Gig)

After a good amount of digging I found that the memory usage is is all
in System.String and contained within the pricing object. This object
makes extensive use of a single string object which is passed as an OUT
parameter to a Interop (unmanaged) object.

There are approximately 30 calls to the unmanaged interop object within
the class, and the class is called upwards of 3-4 times per second. I
know that System.Strings are immutable, therefore, I am assuming that
each time this call returns within the class, a new String object is
being created and allocated. The issue is that many of these objects
are being promoted to Gen2 and never being finalized/destroyed by the
GC. The GC apparently assumes that all these string objects are still
alive and will not remove them. I think that this is due to the
frequency at which these objects are being created.

Unfortunately I cannot mitigate the impact using StringBuilder, as the
parameters are OUT string on the interop assembly (this could be
changed by my colleague who wrote it, if neccesary.)

Anyway, does anyone have any idea how to get the memory usage down to a
manageable level?

Kind Regards,
Mike
 
C

Chan Ming Man

Are you talking about web service here? Breakdown and show you code if
possible. At the mean time I can only say do check for the redundant loop
and so.

chanmm
 
M

Marc Gravell

Futher, check also for anything you are doing that might be putting the
string(s) into (for instance) a static container, either directly or
indirectly. As an example, if you have a class that subscribes to a
static event, then because the static delegate can now see your class,
and because static fields are not eligible for collection, thus your
class will never be collected unless you detach the event. Likewise
collections, hashtables, properties, etc.

If your code has an instance that stays alive for a long time (e.g.
visible somewhere under Main() for an app), then the same can also be
true.

A third cause: do you have any async methods that you do not finish
correctly? With delegates you *must* call EndInvoke sooner or later (to
confuse matters, Control.EndInvoke does not suffer this, but I don't
think that this applies here).

Marc
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top