How are String and Char types stored in memory in .NET?

后端 未结 6 1301
自闭症患者
自闭症患者 2020-12-03 18:05

I\'d need to store a language code string, such as \"en\", which will always contains 2 characters.

Is it better to define the type as \"String\" or \"Char\"?

<
6条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-03 18:20

    Short answer: Use string

    Long answer:

    private string languageCode;
    

    AFAIK strings are stored as a length prefixed array of chars. A String object is instantiated on the heap to maintain this raw array. But a String object is much more than a simple array it enables basic string operations like comparison, concatenation, substring extraction, search etc

    While

    private char[] languageCode;
    

    will be stored as an Array of chars i.e. an Array object will be created on the heap and then it will be used to manage your characters. But it still has a length attribute which is stored internally so there are no apparent savings in memory when compared to a string. Though presumably an Array is simpler than a String and may have fewer internal variables thus offering a lower memory foot print (this needs to be verified).

    But OTOH you loose the ability to perform string operations on this char array. Even operations like string comparison become cumbersome now. So long story short use a string!

提交回复
热议问题