System.String memory leaks C# application.

G

Guest

tHi,
I have application with memory leaks and I used .Net memory profiler. It
showed that every time I use string, gc does not clear that string and at the
end I have many instances and bytes allocated for strings. Is there a right
way to use strings?
Or StringBuilder is the answer? THanks
 
G

Guest

hi
Put simply, a string type is immutable and a StringBuilder is NOT.

Immutable means that after created it cannot be modfied, changed, etc. -
This is what a string type is, if you add even just one character to a string
using either the + or &

myString = myString & "HI"

A new string is created (an additional OBJECT is created)

A StringBuilder is NOT immutable (Mutable), so you can add, remove, modify,
etc. a StringBuilder object and new objects will NOT be created. So, if you
need to dynamically construct a string or manipulate one always use a
StringBuilder object.

C# Example:

StringBuilder sb = new StringBuilder("You can pass in a string to the
contstructor");
sb.Append(" and then add some more");

regards
Ansil
Dimensions
Technopark TVM
(e-mail address removed)
 
N

Nick Malik

Hi Tony,

It's not really a memory leak as much as it is memory usage. The gc will
eventually pick up all the strings. You don't control the logic of the gc.

As the other responder mentioned, using StringBuilder will make many string
operations far more efficient.

--- Nick
 

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