Encoding.ASCII vs. new ASCIIEncoding()

北战南征 提交于 2020-01-03 15:21:35

问题


If I use:

A) var targetEncodingA = Encoding.ASCII;

and

B) var targetEncodingB = new ASCIIEncoding();

then both targetEncoding0 and targetEncoding1 are of the same type.

Are there any preferred scenarios and/or advantages/disadvantages when to use A or B?

(besides creating new instance by constructor each time I use it)


回答1:


Here is the Encoding.ASCII implement detail (from Encoding.cs):

private static volatile Encoding asciiEncoding;

public static Encoding ASCII
{
  {
    if (Encoding.asciiEncoding == null)
      Encoding.asciiEncoding = (Encoding) new ASCIIEncoding();
    return Encoding.asciiEncoding;
  }
}

The main difference is the return type differs, which depends on what type you wish to use (ASCIIEncoding vs Encoding), and Encoding is the base class.

From a performance perspective, Encoding.ASCII is the preference.




回答2:


I prefer Encoding.ASCII in all cases, it is a static property. It avoids creating a new instance each time it is needed (singleton).

Personnaly, I avoid using the new keyword when possible when a static class can do that for you. I will add that Encoding.ASCII is shorter to write than new ASCIIEncoding().



来源:https://stackoverflow.com/questions/20880246/encoding-ascii-vs-new-asciiencoding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!