定义
将文本表示为 UTF-16 代码单元的序列。
注解
字符串是用于表示文本的字符的有序集合。 String对象是对象的有序集合 System.Char ,表示字符串; System.Char 对象对应于 utf-16 代码单元。 对象的值 String 是对象的顺序集合的内容 System.Char ,并且该值是不可变的 (也就是说,它是只读)
测试
1、修改值
因为是只读的,那么如果对它进行赋值的话其实是给它分配了另外的内存地址
测试实例:
public string GetMemory(System.Object o)
{
GCHandle h = GCHandle.Alloc(o, GCHandleType.Pinned);
IntPtr addr = h.AddrOfPinnedObject();
return "0x" + addr.ToString("X");
}
string s = "aa";
Debug.LogError(GetMemory(s));
Debug.LogError("---------------");
s = "bb";
Debug.LogError(GetMemory(s));
Debug.LogError("---------------");
输出结果:
2、执行字符串拼接消耗
void testStringConnect(int num) {
string str = "";
for (int i = 0; i < num; i++) {
str += i.ToString();
}
}
void testStringBuilder(int num) {
System.Text.StringBuilder build = new System.Text.StringBuilder();
for (int i = 0; i < num; i++)
{
build.Append(i.ToString());
}
}
int start = Environment.TickCount;
testStringConnect(10000);
int connect = Environment.TickCount;
testStringBuilder(10000);
int endTime = Environment.TickCount;
Debug.LogErrorFormat("运行 10000 次耗时 connectCostTime:{0},buildCostTime:{1}", connect-start,endTime-connect);
执行消耗: