What is the difference between String.Empty and “” (empty string)?

后端 未结 17 1963
礼貌的吻别
礼貌的吻别 2020-11-22 03:25

In .NET, what is the difference between String.Empty and \"\", and are they interchangable, or is there some underlying reference or Localization i

17条回答
  •  情书的邮戳
    2020-11-22 04:06

    The previous answers were correct for .NET 1.1 (look at the date of the post they linked: 2003). As of .NET 2.0 and later, there is essentially no difference. The JIT will end up referencing the same object on the heap anyhow.

    According to the C# specification, section 2.4.4.5: http://msdn.microsoft.com/en-us/library/aa691090(VS.71).aspx

    Each string literal does not necessarily result in a new string instance. When two or more string literals that are equivalent according to the string equality operator (Section 7.9.7) appear in the same assembly, these string literals refer to the same string instance.

    Someone even mentions this in the comments of Brad Abram's post

    In summary, the practical result of "" vs. String.Empty is nil. The JIT will figure it out in the end.

    I have found, personally, that the JIT is way smarter than me and so I try not to get too clever with micro-compiler optimizations like that. The JIT will unfold for() loops, remove redundant code, inline methods, etc better and at more appropriate times than either I or the C# compiler could ever anticipate before hand. Let the JIT do its job :)

提交回复
热议问题