string 在进行运算时(如赋值、拼接等)会产生一个新的实例,而 stringbuilder 则不会。所以在大量字符串拼接或频繁对某一字符串进行操作时最好使用 stringbuilder,不要使用 string
另外,对于 string 我们不得不多说几句:
1.它是引用类型,在堆上分配内存
2.运算时会产生一个新的实例
3.string 对象一旦生成不可改变(immutable)
3.定义相等运算符(== 和 !=)是为了比较 string 对象(而不是引用)的值
示例:
using system;
using system.collections.generic;
using system.text;
namespace example22
{
class program
{
static void main(string[] args)
{
const int cycle = 10000;
long vtickcount = environment.tickcount;
string str = null;
for (int i = 0; i < cycle; i++)
str += i.tostring();
console.writeline("string: {0} msel", environment.tickcount - vtickcount);
vtickcount = environment.tickcount;
//看到这个变量名我就生气,奇怪为什么大家都使它呢? :)
stringbuilder sb = new stringbuilder();
for (int i = 0; i < cycle; i++)
sb.append(i);
console.writeline("stringbuilder: {0} msel", environment.tickcount - vtickcount);
string tmpstr1 = "a";
string tmpstr2 = tmpstr1;
console.writeline(tmpstr1);
console.writeline(tmpstr2);
//注意后面的输出结果,tmpstr1的值改变并未影响到tmpstr2的值
tmpstr1 = "b";
console.writeline(tmpstr1);
console.writeline(tmpstr2);
console.readline();
}
}
}
结果:
string: 375 msel
stringbuilder: 16 msel
a
a
a