473,770 Members | 1,991 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

StringBuilder and internal memory question

DV
I have a StringBuilder that has a string with 12,000,000 characters.
When I do a ToString(), I expect to have ~25,000,000 bytes worth of
memory, yet, I end up with ~43,000,000 bytes. That's almost double
the size. The string returned from ToString() is actually of size
StringBuilder.C apacity, NOT StringBuilder.L ength. It may have a
end-of-string character at StringBuilder.L ength, but its actual memory
size is StringBuilder.C apacity.

Does this sound right?

Mar 1 '06
15 2814
DV
Thanks all... I think i got it...
Interestingly enough..

If I do...
StringBuilder sb = new StringBuilder(1 0000000);
for (int i=0; i<100; i++)
sb.Append("Hell o World");
string a1 = sb.ToString();

and..
StringBuilder sb = new StringBuilder() ;
for (int i=0; i<100; i++)
sb.Append("Hell o World");
string a2 = sb.ToString();

in this case, a1 actually takes LESS physical memory then a2. a1 gets
trimmed while a2 returns the internal string.
i guess the lesson is to put a capacity whenever possible. but that
also has drawbacks..

Mar 2 '06 #11
Willy Denoyette [MVP] <wi************ *@telenet.be> wrote:
Hit send too fast.
The String reference returned from SB.ToString() is just the same reference
to the existing String object, trimming would involve the creation of a new
string, this would increase the memory footprint and would take a
performance hit.


Exactly - so the OP's supposition that "The string returned from
ToString() is actually of size StringBuilder.C apacity, NOT
StringBuilder.L ength" sounds right to me.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Mar 2 '06 #12

"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
| Willy Denoyette [MVP] <wi************ *@telenet.be> wrote:
| > Hit send too fast.
| > The String reference returned from SB.ToString() is just the same
reference
| > to the existing String object, trimming would involve the creation of a
new
| > string, this would increase the memory footprint and would take a
| > performance hit.
|
| Exactly - so the OP's supposition that "The string returned from
| ToString() is actually of size StringBuilder.C apacity, NOT
| StringBuilder.L ength" sounds right to me.
|

Not really, what delimits a string is it's Length, the fact that the string
buffer (char[]) is larger is due to the way SB's handle the underlying
'String', they can add char's to the buffer without the need to create a new
String object (until the buffer is filled completely), which is the reason
why SBs exist. What is returned by SB.ToString() is a String reference and
what counts is the Length property value, what's stored beyond is not part
of the String, there isn't a managed way to get at the size of the buffer,
nor can you get at the contents of the store beyond the last char position +
1 (the 0x0000 terminator) in the buffer.
But this was not really my point, the OP assumes that the capacity is 43MB
for a string of 12000000 which is definitely not true.

Willy.
Mar 2 '06 #13
Willy Denoyette [MVP] wrote:
| Exactly - so the OP's supposition that "The string returned from
| ToString() is actually of size StringBuilder.C apacity, NOT
| StringBuilder.L ength" sounds right to me.

Not really, what delimits a string is it's Length, the fact that the string
buffer (char[]) is larger is due to the way SB's handle the underlying
'String', they can add char's to the buffer without the need to create a new
String object (until the buffer is filled completely), which is the reason
why SBs exist. What is returned by SB.ToString() is a String reference and
what counts is the Length property value, what's stored beyond is not part
of the String, there isn't a managed way to get at the size of the buffer,
nor can you get at the contents of the store beyond the last char position +
1 (the 0x0000 terminator) in the buffer.
No - but given the rest of the OP's question, I thought it reasonable
to assume that the "size" he's talking about is the size in memory, not
the "logical" length of the string. Given that reading, isn't the OP's
supposition valid? The "buffer size" (in characters) of the returned
string is the same as (or maybe one or two characters more or less -
not sure) the capacity of the StringBuilder it was returned from.

Even though you can't get at the rest of the buffer, I'd say it still
"counts" in terms of being valuable information. For instance, if you
were creating a lot of long-lived strings from StringBuilders, it may
be worth creating a copy of the string which effectively trims the
extra buffer, allowing the oversized string to then be garbage
collected. (I've done this many times in Java, particularly when
reading lines from a file. The initial buffer is 80 characters, and if
you're reading a dictionary a line at a time and the average line
length is only 5 or 6 characters, the wastage can be very, very
significant.)
But this was not really my point, the OP assumes that the capacity is 43MB
for a string of 12000000 which is definitely not true.


That much is certainly true - *if* by "string of 12000000" you mean a
"string of internal buffer size 12000000 characters".

Jon

Mar 2 '06 #14

"DV" <da*****@gmail. com> wrote in message
news:11******** **************@ u72g2000cwu.goo glegroups.com.. .
| Thanks all... I think i got it...
| Interestingly enough..
|
| If I do...
| StringBuilder sb = new StringBuilder(1 0000000);
| for (int i=0; i<100; i++)
| sb.Append("Hell o World");
| string a1 = sb.ToString();
|
| and..
| StringBuilder sb = new StringBuilder() ;
| for (int i=0; i<100; i++)
| sb.Append("Hell o World");
| string a2 = sb.ToString();
|
| in this case, a1 actually takes LESS physical memory then a2. a1 gets
| trimmed while a2 returns the internal string.
| i guess the lesson is to put a capacity whenever possible. but that
| also has drawbacks..
|

Right, what you see here is the result of an optimization.
Let me try to explain what's happening ....

First you need to know how a SB and a String looks like on the managed heap,
this is how a StringBuilder object looks:

<standard object header> // to IntPtr sized values, not relevant here
IntPtr m_currentThread ;
int m_maxCapacity;
string m_StringValue;

while a String looks like:
<object header>
int m_arrayLength;
int m_stringLength;
char m_firstChar;

In the first case, you create a SB with capacity 10000000, that means that
the size of the underlying String object is larger than 85Kb, so, the String
will end on the Large Object Heap (LOH).
Then you start filling the string buffer, the result at the end of the loop
looks like:

Your StrinBuilder sb on the Gen0 heap

m_currentThread = xxxx // not important here
m_maxCapacity = 2147483647 // 2GB
m_StringValue = 03271000 // reference - points to a string on the
LOH (value as a sample)

m_arrayLength = 10000001 // Buffer space (in no. of char)
m_stringLength = 1100 // actual string Length
m_firstChar = 'H' // First char in buffer (start of buffer
.... // following chars
.... = 'd' // last char of string (buffer position 1100)
.... = 0x0000 // last char in buffer (buffer position 1101)

Now when you execute ... sb.ToString();
the CLR rightfully decides that this String object doesn't belong to the LOH
(is < 85Kb), so he creates a new String on the Gen0 heap and returns it's
reference in a1, the new string object looks now like:

m_arrayLength = 1101 // Buffer space (in no. of char)
m_stringLength = 1100 // actual string Length
m_firstChar = 'H' // First char in buffer (start of buffer
.... // following chars
.... = 'd' // last char of string (buffer position 1100)
.... = 0x0000

Notice the new m_arrayLength of 1100 ...
Note that the m_arrayLength = 10000001 has never been committed, only
reserved that is why you don't see this allocated in physical memory.


What's happening in the second case is:

A SB is created on the Gen0 heap and looks like:

m_currentThread = xxxx // not important here
m_maxCapacity = 2147483647 // 2GB
m_StringValue = 01274e34 // reference - points to a string on the Gen0
heap(value as a sample)

and the underlying String object at the end of the loop:

m_arrayLength = 2049 // Buffer space (in no. of char)
m_stringLength = 1100 // actual string Length
m_firstChar = 'H' // First char in buffer (start of buffer
.... // following chars
.... = 'd' // last char of string (buffer position 1100)
.... = 0x0000

Notice the m_arrayLength ...

But before you get this final string, a number of temporary strings need to
be build. Remember that the SB starts with an m_arrayLength = 17 (16 + 1 for
the 0x0000 string termination char).
That means that after the loop you have effectively created 8 intermediate
string objects (16, 32, 64, ...2048).
That means that you have wasted some memory, but also some CPU cycles, more,
you also put some additional stress on the GC which will have to clean-up
the intermediate objects.
Conclusion: you should try to pre-allocate SB's whenever possible. Note that
this is especially important for server applications and for client
(WinForms) applications that need to run in Terminal Server environments.
Hope this clears things up a bit :-)

Willy.


Mar 2 '06 #15
Jon, you should read his original question, that starts with ...
I have a StringBuilder that has a string with 12,000,000 characters.


"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:11******** **************@ j33g2000cwa.goo glegroups.com.. .
| Willy Denoyette [MVP] wrote:
| > | Exactly - so the OP's supposition that "The string returned from
| > | ToString() is actually of size StringBuilder.C apacity, NOT
| > | StringBuilder.L ength" sounds right to me.
| >
| > Not really, what delimits a string is it's Length, the fact that the
string
| > buffer (char[]) is larger is due to the way SB's handle the underlying
| > 'String', they can add char's to the buffer without the need to create a
new
| > String object (until the buffer is filled completely), which is the
reason
| > why SBs exist. What is returned by SB.ToString() is a String reference
and
| > what counts is the Length property value, what's stored beyond is not
part
| > of the String, there isn't a managed way to get at the size of the
buffer,
| > nor can you get at the contents of the store beyond the last char
position +
| > 1 (the 0x0000 terminator) in the buffer.
|
| No - but given the rest of the OP's question, I thought it reasonable
| to assume that the "size" he's talking about is the size in memory, not
| the "logical" length of the string. Given that reading, isn't the OP's
| supposition valid? The "buffer size" (in characters) of the returned
| string is the same as (or maybe one or two characters more or less -
| not sure) the capacity of the StringBuilder it was returned from.
|
| Even though you can't get at the rest of the buffer, I'd say it still
| "counts" in terms of being valuable information. For instance, if you
| were creating a lot of long-lived strings from StringBuilders, it may
| be worth creating a copy of the string which effectively trims the
| extra buffer, allowing the oversized string to then be garbage
| collected. (I've done this many times in Java, particularly when
| reading lines from a file. The initial buffer is 80 characters, and if
| you're reading a dictionary a line at a time and the average line
| length is only 5 or 6 characters, the wastage can be very, very
| significant.)
|
| > But this was not really my point, the OP assumes that the capacity is
43MB
| > for a string of 12000000 which is definitely not true.
|
| That much is certainly true - *if* by "string of 12000000" you mean a
| "string of internal buffer size 12000000 characters".
Jon,
The OP asked....
I have a StringBuilder that has a string with 12,000,000 characters.

And I replied with .. you will end with a SB buffer (a String) with a
Capacity of 16777216 and a
Length of 12000000.

You see, the capacity of a SB holding a string with Length 12000000 is
always 16777216 or 33554432 bytes unless you pre-allocate the SB.
The SB does not consume 43MB in this case. Actually the OP doesn't know the
size of the SB at all, he is simply watching the memory counters in Taskman
I'm sure, these don't reveal the size of whatever object in memory. And
that's my point. Sorry if I'm confusing you ;-)
Willy.
Mar 2 '06 #16

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

37
4719
by: Kevin C | last post by:
Quick Question: StringBuilder is obviously more efficient dealing with string concatenations than the old '+=' method... however, in dealing with relatively large string concatenations (ie, 20-30k), what are the performance differences (if any with something as trivial as this) between initializing a new instance of StringBuilder with a specified capacity vs. initializing a new instance without... (the final length is not fixed) ie,
12
7399
by: | last post by:
I know how to use a StringBuilder, which supposedly does not create a new copy of it each time you modify it contents by adding or removing text. But, I wonder how does it do that internally ? I was planning to use a stringbuilder to hold big amounts of text, with several megs o size, to be read later based on fixed offsets, so I need to know if this is suitable for it.
7
958
by: KH | last post by:
API question... Why doesn't StringBuilder have IndexOf and other similar methods like String? I can't think of a good reason off the top of my head. Easy to write helper functions to do the same thing, but sure would be helpful in certain cases. KH
33
4690
by: genc_ymeri | last post by:
Hi over there, Propably this subject is discussed over and over several times. I did google it too but I was a little bit surprised what I read on internet when it comes 'when to use what'. Most of articles I read from different experts and programmers tell me that their "gut feelings" for using stringBuilder instead of string concatenation is when the number of string concatunation is more then N ( N varies between 3 to max 15 from...
12
2716
by: Richard Lewis Haggard | last post by:
I thought that the whole point of StringBuilder was that it was supposed to be a faster way of building strings than string. However, I just put together a simple little application to do a comparative analysis between the two and, surprisingly, string seems to out perform StringBuilder by a significant amount. A string concatenation takes not quite twice as long using StringBuilder than it does with a string. This doesn't sound right to...
26
3206
by: Hardy Wang | last post by:
Hi all, I know it is better to handle large string with a StringBuilder, but how does StringBuilder class improve the performance in the background? Thanks! -- WWW: http://hardywang.1accesshost.com ICQ: 3359839 yours Hardy
34
3557
by: raylopez99 | last post by:
StringBuilder better and faster than string for adding many strings. Look at the below. It's amazing how much faster StringBuilder is than string. The last loop below is telling: for adding 200000 strings of 8 char each, string took over 25 minutes while StringBuilder took 40 milliseconds! Can anybody explain such a radical difference?
0
9454
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10101
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10038
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9906
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7456
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6710
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5354
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5482
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4007
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.