我应该尽可能尝试使用const字符串而不是字符串吗?

时间:2013-11-07 20:44:37

标签: c# .net optimization il

考虑以下三个例子:

示例A

string message = "Hello world!";
throw new System.Exception(message);

例B

const string message = "Hello world!";
throw new System.Exception(message);

示例C

throw new System.Exception("Hello world!");

有没有理由使用其中一个?具体来说,我不应该尽可能使用const字符串(假设字符串永远不会被修改),因此例B最好吗?例C中会发生什么?

我想我是在询问上面发出的IL是相同还是不同,如果有任何差异。我认识到差异很小,可能无需担心;我想这是一个学术问题。


编辑。这是IL

IL_0014: ldstr "This is a string"
IL_0019: stloc.0
IL_001a: ldloc.0
IL_001b: newobj instance void [mscorlib]System.Exception::.ctor(string)
IL_0020: throw


IL_0033: nop
IL_0034: ldstr "This is a const string"
IL_0039: newobj instance void [mscorlib]System.Exception::.ctor(string)
IL_003e: throw

IL_0051: nop
IL_0052: ldstr "This is an inline string."
IL_0057: newobj instance void [mscorlib]System.Exception::.ctor(string)
IL_005c: throw

看起来与我完全相同。

2 个答案:

答案 0 :(得分:1)

取决于背景,真的。这条消息会改变吗?如果你使用选项A,你有机会修改字符串消息的值,而另外两个你正在打印一个硬编码的字符串 - 这很好,如果它总是说那个

答案 1 :(得分:0)

在性能,内存使用或字符串表效率方面没有区别。

const关键字的唯一作用是在重新分配字符串时生成编译时错误。因此,添加const以向其他开发人员传达您的意图是有帮助的。