String.Empty read only instead of a constant?
如果你将任何字符串设为常量,那么编译器会在你调用它的任何地方替换为实际的字符串,然后你会用相同的字符串填充你的代码。代码运行也需要从不同的内存数据中反复读取那个字符串。
如果您将字符串只保留在一个位置,因为它是String.Empty,程序只将相同的字符串保留在一个位置并读取它,或者引用它 - 将内存中的数据保持在最低限度。
此外,如果您使用 String.Empty 作为 const 编译任何 dll,并且由于任何原因 String.Empty 更改,则编译后的 dll 将不再工作,因为 cost 使内部代码实际在每次调用时保留字符串的副本。
例如看这段代码:
public class OneName
{
const string cConst = "constant string";
static string cStatic = "static string";
readonly string cReadOnly = "read only string";
protected void Fun()
{
string cAddThemAll ;
cAddThemAll = cConst;
cAddThemAll = cStatic ;
cAddThemAll = cReadOnly;
}
}
将由编译器作为:
public class OneName
{
// note that the const exist also here !
private const string cConst = "constant string";
private readonly string cReadOnly;
private static string cStatic;
static OneName()
{
cStatic = "static string";
}
public OneName()
{
this.cReadOnly = "read only string";
}
protected void Fun()
{
string cAddThemAll ;
// look here, will replace the const string everywhere is finds it.
cAddThemAll = "constant string";
cAddThemAll = cStatic;
// but the read only will only get it from "one place".
cAddThemAll = this.cReadOnly;
}
}
和程序集调用
cAddThemAll = cConst;
0000003e mov eax,dword ptr ds:[09379C0Ch]
00000044 mov dword ptr [ebp-44h],eax
cAddThemAll = cStatic ;
00000047 mov eax,dword ptr ds:[094E8C44h]
0000004c mov dword ptr [ebp-44h],eax
cAddThemAll = cReadOnly;
0000004f mov eax,dword ptr [ebp-3Ch]
00000052 mov eax,dword ptr [eax+0000017Ch]
00000058 mov dword ptr [ebp-44h],eax
编辑:更正错字