2.老生常谈:Strings and String Builders

本文探讨了.NET Framework中字符串的不可变性及其对性能的影响,并介绍了如何使用StringBuilder类来创建动态字符串,以减少垃圾回收并提高应用程序效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

书目:MCTS 70-536: TS: .NET Framework 2.0-Application Development Foundation 
章节:Chapter 1: Framework Fundamentals -- Lesson 2: Using Common Reference Types -- Strings and String Builders
原文内容:
Strings of type System.String are immutable in .NET. That means any change to a string
causes the runtime to create a new string and abandon the old one. That happens
invisibly, and many programmers might be surprised to learn that the following code
allocates four new strings in memory:
None.gif //  C#
None.gif
string  s;
None.gif
=   " wombat " //  "wombat"
None.gif
+=   "  kangaroo " //  "wombat kangaroo"
None.gif
+=   "  wallaby " //  "wombat kangaroo wallaby"
None.gif
+=   "  koala " //  "wombat kangaroo wallaby koala"
None.gif
Console.WriteLine(s);

Only the last string has a reference; the other three will be disposed of during garbage
collection. Avoiding these types of temporary strings helps avoid unnecessary garbage
collection, which improves performance. There are several ways to avoid temporary
strings:
      1.Use the String class’s Concat, Join, or Format methods to join multiple items in a
single statement.
      2.Use the StringBuilder class to create dynamic (mutable) strings.

The StringBuilder solution is the most flexible because it can span multiple statements.
The default constructor creates a buffer 16 bytes long, which grows as needed.
You can specify an initial size and a maximum size if you like. The following code demonstrates
using StringBuilder:

None.gif //  C#
None.gif
System.Text.StringBuilder sb  =   new  System.Text.StringBuilder( 30 );
None.gifsb.Append(
" wombat " );  //  Build string.
None.gif
sb.Append( "  kangaroo " );
None.gifsb.Append(
"  wallaby " );
None.gifsb.Append(
"  koala " );
None.gif
string  s  =  sb.ToString();  //  Copy result to string.
None.gif
Console.WriteLine(s);

Another subtle but important feature of the String class is that it overrides operators
from System.Object. Table 1-4 lists the operators the String class overrides.


参考文章:
http://www.codeproject.com/Purgatory/string.asp
http://channel9.msdn.com/ShowPost.aspx?PostID=14932

转载于:https://www.cnblogs.com/jailu/archive/2007/02/14/650551.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值