What's the use of System.String.Copy in .NET?

前端 未结 8 978
误落风尘
误落风尘 2020-12-13 07:58

I\'m afraid that this is a very silly question, but I must be missing something.

Why might one want to use String.Copy(string)?

The documentation says the me

8条回答
  •  青春惊慌失措
    2020-12-13 08:39

    I am not sure how String being implemented in .NET, but I think Java is a good reference.

    In Java, new String(str) also do what String.copy(str); do, allocate a new String with same value.

    It seem useless but it is very useful in memory optimization.

    String contains a char[] with offset and length in the implementation. If you do a something like a substring, it won't do a memory copy but return a new String instance sharing same char[]. In many cases, this pattern will save a lot of memory copy and allocation. However, if you substring a small piece within a long large String. It will still reference to large char[] even the original large String is able to be GC.

    String longString = // read 1MB text from a text file
    String memoryLeak = largeString.substring(100,102); 
    largeString=null;
    // memoryLeak will be sized 1MB in the memory
    String smaller = new String(largeString.substring(100,102));
    // smaller will be only few bytes in the memory
    

    It can force the new String object allocate it's own char[] to prevent hidden memory leak/waste.

提交回复
热议问题