StringBuilder and PCHAR*

S

Schley Andrew Kutz

I am iterating through 454 rows of a table and with each row I use the ID
field to form a URI for a contact in a public folder on my exchange server.

My memory keeps growing though. I think it is because I reconstruct my URI
each time. I have done this 2 ways and I want to know something. How is
this ...

StringBuilder sb = new StringBuilder( 255, 255 );
for ( int x = 0; x < rs.Rows.Count; ++x )
{
if ( sb.Length > 0 ) sb.Remove( 0, sb.Length );
sb.AppendFormat( "{0}/{1}.EML", URI_PREFIX, rs.Rows[ x ][ "ID" ] );
...
}

any more efficient than this

for ( int x = 0; x < rs.Rows.Count; ++x )
string uri = string.Format( "{0}/{1}.EML", URI_PREFIX, rs.Rows[ x ][
"ID" ] );

The first snippet should be far more effective since I am pre-allocating my
buffer. However, since the ADODB.Connection object takes a string as its
connection source and string are immutable in dot net, whenever I call the
ToString method of the StringBuilder to give to the connection object, it is
going to allocate new memory for that string, correct?

I have found no way in C# to make sequential string operations occupy the
same memory. This is just plain wasteful.

Where in the hell then is the efficiency in this? Why is this better than C
or C++ where you can pass a pointer to an array of char so that you do not
re-create a string in memory from a buffer you pre-allocated for this very
reason to give to a function?

-a
 
M

Mattias Sjögren

whenever I call the
ToString method of the StringBuilder to give to the connection object, it is
going to allocate new memory for that string, correct?

I can't find something to back it up at the moment, but I'm pretty
sure I've read that the runtime can optimize this by "detatching" the
memory used by the StringBuilder and turning it into a String, without
allocating new memory.



Mattias
 
S

Schley Andrew Kutz

Mattias,

I think I know to what you refer. The StringBuilder does detach the buffer
to static memory when you call ToString the first time and each subsequent
call uses that formed string, but the documentation says if you "alter the
buffer" the next time you call ToString a new string will get created in
memory.

What it is unclear on is if that means the contents of the buffer, or the
size of the buffer.

Ideas?

-a
 

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